Reputation: 141
I have an issue trying to clear a read-only variable in a Perl regex. Here is a sample code:
while (<$input>) {
$cap = "";
$_ =~ s/(.*)"(hello)(.*)"(.*)/$1$2$4/;
$cap = $2;
print "$_\n";
print "captured $cap\n";
}
This is fine until the line it's reading does not have "hello".
For some reason, even if the regex didn't match anything, $2
still remains as "hello".
I tried using:
$2 = "";
But, I get a:
Modification of a read-only value attempted
Any suggestions on how to clear the variable?
Upvotes: 5
Views: 168
Reputation: 132832
Perl only resets the match variables on a successful match (or the end of the dynamic scope). This way, it saves a bit of time with all the bookkeeping involved. As such, you should only use the match variables once you know you have a successful match, which is what @toolic shows in their answer.
From perlvar's "Scoping Rules of Regex Variables":
The variables themselves are global and unscoped, but the data they access is scoped similarly to dynamically scoped variables, in that every successful match behaves as though it localizes a global state object to the current block or file scope.
which it goes on to explain as
Notice that each successful match in the exact same scope overrides the match context of the previous successful match, but that unsuccessful matches do not.
Upvotes: 0
Reputation: 62096
Rather than clearing the variable, check if the match was successful:
while (<$input>) {
$cap = "";
if ($_ =~ s/(.*)"(hello)(.*)"(.*)/$1$2$4/) {
$cap = $2;
}
print "$_\n";
print "captured $cap\n";
}
Upvotes: 5