Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl 6 regex not terminated

Tags:

regex

raku

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?

like image 495
BhaskarS Avatar asked Dec 29 '17 13:12

BhaskarS


2 Answers

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.

like image 180
smls Avatar answered Oct 17 '22 21:10

smls


A hash # is used as a comment marker in Perl 6 regexes.

Add a backslash \ to escape it like this

if ( $line =~ /^\s*\#/ )
like image 41
Ronan Boiteau Avatar answered Oct 17 '22 21:10

Ronan Boiteau