note
ikegami
<p>Similarly, I've started noticing issues with the common practice of doing <c>local $_</c>. In some situations, that's not enough to prevent damage to the caller. Using <c>local *_</c> fixes those problems. For example, consider the following function:
<c>
sub dequote {
local $_ = @_ ? $_[0] : $_;
s/^"//;
s/"$//;
s/\\(.)/$1/g;
return $_;
}
</c>
<p>It assigns its parameter (or $_ if there are no parameters) to $_. It attempts to prevent damage to the caller by localizing $_ first, but I will show it doesn't always work.
<h3>Case 1</h3>
<p>$_ is tied, or $_ is an alias to something which is tied.
<p>
<readmore>
Running
<c>
use strict;
use warnings;
sub dequote {
local $_ = @_ ? $_[0] : $_;
s/^"//;
s/"$//;
s/\\(.)/$1/g;
return $_;
}
{
package MyTie;
sub TIESCALAR { bless(\my $var, shift) }
sub FETCH { my $self = shift;
print("FETCH\n"); return $$self; }
sub STORE { my $self = shift; $$self = shift;
print("STORE $$self\n"); return $$self;}
}
tie my $var, 'MyTie';
$var = '"John \"Foo\" Bar"';
print dequote, "\n"
foreach $var;
</c>
<p>gives
<c>
STORE "John \"Foo\" Bar"
FETCH
STORE
FETCH
Use of uninitialized value in concatenation (.) or string at 561931.pl line 18.
STORE
FETCH
Use of uninitialized value in substitution (s///) at 561931.pl line 6.
FETCH
Use of uninitialized value in substitution (s///) at 561931.pl line 7.
FETCH
Use of uninitialized value in substitution (s///) at 561931.pl line 8.
FETCH
STORE
Use of uninitialized value in print at 561931.pl line 25.
</c>
</readmore>
<h3>Case 2</h3>
<p>pos($_) is used by the caller.
<p>
<readmore>
Running
<c>
use strict;
use warnings;
sub dequote {
local $_ = @_ ? $_[0] : $_;
s/^"//;
s/"$//;
s/\\(.)/$1/g;
return $_;
}
$_ = 'abcd';
/\G .. /gcx;
print(pos(), "\n");
dequote('"John \"Foo\" Bar"');
print(pos(), "\n");
</c>
<p>gives
<c>
2
Use of uninitialized value in print at 561931.pl line 18.
</c>
<p>Changing
<br><c> local $_ = @_ ? $_[0] : $_;</c>
<br>to
<br><c> my $s = @_ ? $_[0] : $_;</c>
<br><c> local *_ = \$s;</c>
<br>gives
<c>
2
2
</c>
</readmore>
<h3>The Solution</h3>
<c>
sub dequote {
#local $_ = @_ ? $_[0] : $_; # XXX
my $s = @_ ? $_[0] : $_; # Fix
local *_ = \$s; # Fix
s/^"//;
s/"$//;
s/\\(.)/$1/g;
return $_;
}
</c>
<p>
<readmore>
After making that change, the programs output
<c>
STORE "John \"Foo\" Bar"
FETCH
John "Foo" Bar
</c>
<p>and
<c>
2
2
</c>
<p>respectively.
</readmore>
561895
561895