Perl 6 regex not completed

I have Perl 6 code where I do the following:

if ($line ~~ /^\s*#/) { print "matches\n"; } 

I get 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 Perl 5 code:

 if ($line =~ /^\s*#/) 

It worked great to identify lines with extra space and # .

What causes this error in Perl 6?

+5
source share
2 answers

The hash # used as a comment marker in Perl 6 regular expressions.

Add backslash \ to avoid this.

 if ( $line =~ /^\s*\#/ ) 
+3
source

In Perl 6, everything from a single 1 # to the end of a line is considered a comment, even inside regular expressions.

To avoid this, make it a string literal by placing it inside quotation marks:

 if $line ~~ / ^ \s* '#' / { say "matches"; } 

(Escaping with \ should also work, but Rakudo seems to have a parsing error that makes it unusable when space precedes. And quoting a character, as shown here, is the recommended way, anyway; Perl 6 specifically introduced the quoted strings inside regular expressions and made spaces insignificant by default to avoid the mess of the backslash that many Perl regular expressions suffer from 5.)

More generally, all non-letter characters must be quoted or escaped inside Perl 6 regular expressions to match them literally.
This is another deliberate change not related to backward compatibility with Perl 5, where it is a bit more complicated. Perl 6 has a simple rule:

  • alphanumeric β†’ literally matches only when it was not possible to avoid.
    (When shielded, they either have special meanings, such as \s , etc., or are prohibited.)

  • non-alphanumeric -> matches literally only when escaping.
    (If they are not shielded, they either have special meanings, for example . , + , # , Etc., or are prohibited.)


1 β€œLone” does not mean part of a larger token, such as a quoted string or opening element inline comment .

+8
source

Source: https://habr.com/ru/post/1274384/


All Articles