Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl6 regex not matching end $ character with filenames

Tags:

raku

I've been trying to learn Perl6 from Perl5, but the issue is that the regex works differently, and it isn't working properly.

I am making a test case to list all files in a directory ending in ".p6$"

This code works with the end character

if 'read.p6' ~~ /read\.p6$/ {
    say "'read.p6' contains 'p6'";
}

However, if I try to fit this into a subroutine:

multi list_files_regex (Str $regex) {
  my @files = dir;
  for @files -> $file {
    if $file.path ~~ /$regex/ {
      say $file.path;
    }
  }
}

it no longer works. I don't think the issue with the regex, but with the file name, there may be some attribute I'm not aware of.

How can I get the file name to match the regex in Perl6?

like image 480
con Avatar asked Jan 07 '19 22:01

con


1 Answers

Regexes are a first-class language within Perl 6, rather than simply strings, and what you're seeing here is a result of that.

The form /$foo/ in Perl 6 regex will search for the string value in $foo, so it will be looking, literally, for the characters read\.p6$ (that is, with the dot and dollar sign).

Depending on the situation of the calling code, there are a couple of options:

  1. If you really are receiving regexes as strings, for example read as input or from a file, then use $file.path ~~ /<$regex>/. This means it will treat what's in $regex as regex syntax.
  2. If you will just be passing a range of different regexes in, change the parameter to be of type Regex, and then do $file.path ~~ $regex. In this case, you'd pass them like list_files_regex(/foo/).

Last but not least, dir takes a test parameter, and so you can instead write:

for dir(test => /<$regex>/) -> $file {
    say $file.path;
}
like image 92
Jonathan Worthington Avatar answered Oct 16 '22 06:10

Jonathan Worthington