I have a Perl 6 code where I am doing the following:
if ($line ~~ /^\s*#/) { print "matches\n"; }
I'm getting this error:
===SORRY!===
Regex not terminated.
at line 2
------> <BOL>�<EOL>
Unable to parse regex; couldn't find final '/'
at line 2
------> <BOL>�<EOL>
expecting any of:
infix stopper
This is part of a Perl 5 code:
if ($line =~ /^\s*#/)
It used to work fine to identify lines that have an optional space and a #
.
What's causing this error in Perl 6?
In Perl 6, everything from a lone1#
to the end of the line is considered a comment, even inside regexes.
To avoid this, make it a string literal by placing it inside quotes:
if $line ~~ / ^ \s* '#' / { say "matches"; }
(Escaping with \
should also work, but Rakudo seems to have a parsing bug which makes that not work when preceded by a space.
And quoting the character as shown here is the recommended way anyway – Perl 6 specifically introduced quoted strings inside regexes and made spaces insignificant by default, in order to avoid the backslash clutter that many Perl 5 regexes suffer from.)
More generally, all non-alphanumeric characters need to be quoted or escaped inside Perl 6 regexes in order to match them literally.
This is another deliberate non-backwards-compatible change from Perl 5, where this is a bit more complicated.
In Perl 6 there is a simple rule:
alphanumeric --> matches literally only when not escaped.
(When escaped, they either have special meanings, e.g. \s
etc., or are forbidden.)
non-alphanumeric --> matches literally only when escaped.
(When not escaped, they either have special meanings, e.g. .
, +
, #
, etc., or are forbidden.)
1 'Lone' meaning not part of a larger token such as a quoted string or the opener of an embedded comment.
A hash #
is used as a comment marker in Perl 6 regexes.
Add a backslash \
to escape it like this
if ( $line =~ /^\s*\#/ )
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