[Purdue-pm] example Perl 6 program

Mark Senn mark at purdue.edu
Fri Mar 31 07:43:16 PDT 2017


#!/home/pier/e/mark/src/rakudo-star-2016.11/install/bin/perl6
#
#  I like to use Asian quotes to 「quote things verbatim」.
#
#  On lines that match the Perl 6 regex 「/^\s*url\s*'='/」
#  this program changes
#      OLD    NEW
#      _      \_
#      &      \&
#  but does not change any of these
#      \_
#      {_}
#      \&
#      {&}
#
#  THIS CODE HAS A BUG IN IT: 「Å」 gets transformed into 「Å」
#  because information is being read in one encoding and written
#  using another encoding (I think).
#

# Complain if Perl 5 tries to run this program.
use v6;

multi MAIN($ifn, $ofn)  {  Main $ifn, $ofn;  }

sub Main($ifn, $ofn)
{
    ($ifn eq $ofn)  and  die qq/Input file and output file are both "$ifn"/;

    my $ifh = open $ifn, :r  orelse  die qq/Can't open "$ifn" for input./;

    my $ofh = open $ofn, :w  orelse  die qq/Can't open "$ofn" for output./;

    for $ifh.lines -> $_ is copy
    {
        if (m/^\s*url\s*'='/)
        {
            # I like to use Asian quotes to 「quote things verbatim」.
            # Substitute globally
            #     「(<-[\\{]>)」matches anything except 「\」 or 「{」 (call this $0)
            #     「(<[_&]>)」  matches 「_」 or 「&」                 (call this $1)
            # and replace it with $0, followed by 「\」, followed by $1.
            # By default, spaces are ignored in the regex (formerly known as
            # regular expression) but not in the replacement text.
            s:g
            /
                (<-[\\{]>)  # matches anything except 「{」 or 「\」
                (<[_&]>)    # matches 「_」 or 「&」
            /$0\\$1/;
        }
        $ofh.say($_);
    }

    $ofh.close();

    $ifh.close()
}


More information about the Purdue-pm mailing list