On 2016-01-17 Tom Browder <tom.brow...@gmail.com> wrote:
> My question: Is there a way to have Perl 6 do the required escaping
> for the regex programmatically, i.e., turn this:
> 
> my $str = '/home/usr/.cpan';
> 
> into this:
> 
> my regex dirs {
>   \/home\/usr\/\.cpan
> }
> 
> automatically?  

Yes! And it's also simpler than in Perl 5. I Perl 5, you would have to
do something like:

  my $dirs = qr{\Q$str};

but in Perl 6 you just do:

  my $dirs = regex { $str };

because the other behaviour, to interpret the contents of $str as
another regex to match, has more explicit syntax:

  regex { <$another_regex> }

For your initial use-case there is also another shortcut: an array is
interpreted as an alternation, so you could write:

  my @dirs = < /home/user/.cpan /home/tbrowde/.emacs >;
  my $regex = regex { @dirs };

and it would do what your Perl 5 example does.

If you want to be more restrictive, you can anchor the alternation:
  
  my $regex = regex { ^ @dirs };

Here is a complete program:

  use v6;

  my @dirs = < foo bar baz >;

  my $matcher = regex { ^ @dirs $ };

  for $*IN.lines -> $line {
      if $line ~~ $matcher {
          say "<$line> matched";
      }
      else {
          say "<$line> didn't match";
      }
  }

-- 
        Dakkar - <Mobilis in mobile>
        GPG public key fingerprint = A071 E618 DD2C 5901 9574
                                     6FE2 40EA 9883 7519 3F88
                            key id = 0x75193F88

To spot the expert, pick the one who predicts the job will take the
longest and cost the most.

Reply via email to