Similarly, I've started noticing issues with the common practice of doing local $_. In some situations, that's not enough to prevent damage to the caller. Using local *_ fixes those problems. For example, consider the following function:
sub dequote {
local $_ = @_ ? $_[0] : $_;
s/^"//;
s/"$//;
s/\\(.)/$1/g;
return $_;
}
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.
Case 1
$_ is tied, or $_ is an alias to something which is tied.
Running
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;
gives
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.
Case 2
pos($_) is used by the caller.
Running
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");
gives
2
Use of uninitialized value in print at 561931.pl line 18.
Changing
local $_ = @_ ? $_[0] : $_;
to
my $s = @_ ? $_[0] : $_;
local *_ = \$s;
gives
2
2
The Solution
sub dequote {
#local $_ = @_ ? $_[0] : $_; # XXX
my $s = @_ ? $_[0] : $_; # Fix
local *_ = \$s; # Fix
s/^"//;
s/"$//;
s/\\(.)/$1/g;
return $_;
}
After making that change, the programs output
STORE "John \"Foo\" Bar"
FETCH
John "Foo" Bar
and
2
2
respectively.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.