I am trying to extract the first name in a regex, but ~~ seems to want to assign to an immutable container. Why so? What did I do 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 the error I got was this:
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 sub-string of the outer $/ that matches a pattern; why would ~~ be an assignment?
Thank you for your help !!!
You are using the ~~
operator inside a function that already has $/
defined as an argument. Arguments are read-only by default, so the assignment fails.
It should be enough to use if $nameStr.match(/your regex/) -> $/ { ... }
instead of the ~~
operator. You will get a fresh $/
inside the block that'll have the match result you want in it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.