Why is perl6 regex ~~ trying to assign an immutable container?

I'm trying to extract the first name in a regular expression, but ~~ seems to want to assign an immutable container. Why is that? What have I done wrong?

my $test= ' "DOE , JOHN" ';

grammar findReplace {
    regex TOP            { \s* <ptName> \s* }
    regex ptName         { <aName> }
    regex aName          { \" .+? \" }
}

class rsAct {
    method TOP ($/) { make "last name is: " ~ $<ptName>.made; }
    method ptName ($/) { 
        my $nameStr = $/.Str; 
        if $nameStr ~~ m/ \" (<alpha>+) .* \, .* \" / { 
            my $lastName = $/[0];   # I want $/[0] sub-string of outer $/
            make $lastName; 
    }
    }
}

my $m = findReplace.parse($test, actions => rsAct.new);
say $m.made;

and I got the error:

Cannot assign to a readonly variable or a value
  in method ptName at shit.pl line 13
  in regex ptName at shit.pl line 5
  in regex TOP at shit.pl line 4
  in block <unit> at shit.pl line 20

I am trying to get a substring of the outer $ / that matches the pattern; why ~~ be an assignment?

Thank you for your help !!!

+4
source share
1 answer

You use an operator ~~inside a function that already has one $/, defined as an argument. Arguments are read-only by default, so assignment is not performed.

if $nameStr.match(/your regex/) -> $/ { ... } ~~. $/ , , .

+2

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


All Articles