- 论坛徽章:
- 145
|
回复 1# pony2001mx
please refer the perldata and perlvar
$ perldoc perlvar
perlvar - Perl predefined variables
...
A few of these variables are considered "read-only". This means that if
you try to assign to this variable, either directly or indirectly through
a reference, you'll raise a run-time exception.
You should be very careful when modifying the default values of most
special variables described in this document. In most cases you want to
localize these variables before changing them, since if you don't, the
change may affect other modules which rely on the default values of the
special variables that you have changed. This is one of the correct ways
to read the whole file at once:
open my $fh, "<", "foo" or die $!;
local $/; # enable localized slurp mode
my $content = <$fh>;
close $fh;
But the following code is quite bad:
open my $fh, "<", "foo" or die $!;
undef $/; # enable slurp mode
my $content = <$fh>;
close $fh;
since some other module, may want to read data from some file in the
default "line mode", so if the code we have just presented has been
executed, the global value of $/ is now changed for any other code running
inside the same Perl interpreter.
Usually when a variable is localized you want to make sure that this
change affects the shortest scope possible. So unless you are already
inside some short "{}" block, you should create one yourself. For example:
my $content = '';
open my $fh, "<", "foo" or die $!;
{
local $/;
$content = <$fh>;
}
close $fh;
Here is an example of how your own code can go broken:
for ( 1..3 ){
$\ = "\r\n";
nasty_break();
print "$_";
}
sub nasty_break {
$\ = "\f";
# do something with $_
}
You probably expect this code to print the equivalent of
"1\r\n2\r\n3\r\n"
but instead you get:
"1\f2\f3\f"
Why? Because "nasty_break()" modifies $\ without localizing it first. The
value you set in "nasty_break()" is still there when you return. The fix
is to add "local()" so the value doesn't leak out of "nasty_break()":
local $\ = "\f";
It's easy to notice the problem in such a short example, but in more
complicated code you are looking for trouble if you don't localize changes
to the special variables.
|
|