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?
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:
$file.path ~~ /<$regex>/
. This means it will treat what's in $regex
as regex syntax.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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With