Thread Tiefe Hash Strukturen aus Config bilden: Und warum while(<FH>) gefährlich ist (62 answers)
Opened by bloonix at 2006-05-09 17:07

betterworld
 2006-07-09 20:11
#65862 #65862
User since
2003-08-21
2614 Artikel
ModeratorIn

user image
Anscheinend wurde in diesem Thread beschlossen, dass es sicher ist, so zu schreiben:
Code: (dl )
1
2
3
4
5
6
sub foo {
local ($_);
while (<>) {
mach_was_mit($_);
}
}


Aber weit gefehlt! Zusammen mit pq habe ich gerade herausgefunden, dass folgender Code sich äußerst seltsam verhält:
Code: (dl )
1
2
3
4
5
6
7
8
9
10
sub foo {
local ($_);
while (<>) {
chomp;
print "ich habe $_ gelesen\n";
}
}

foo for $1;
print "ende\n";

Wenn man dieses Programm in perl 5.8.8 startet und z. B. "test" eingibt, wird nicht etwa "ich habe test gelesen" ausgegeben, sondern sofort "ende". In perl 5.9.3 hingegen wird abgebrochen mit "Modification of a read-only value attempted at - line 3."

In perlsub steht dazu
Quote
If you localize a special variable, you'll be giving a new value to it,
but its magic won't go away. That means that all side-effects related
to this magic still work with the localized value.

...

the following snippet will die in perl 5.9.0 :

sub f { local $_ = "foo"; print }
for ($1) {
# now $_ is aliased to $1, thus is magic and readonly
f();
}

...

Notably, if you want to work with a brand new value of the default
scalar $_, and avoid the potential problem listed above about $_ previ-
ously carrying a magic value, you should use "local *_" instead of
"local $_".


Ich finde es eigentlich nicht sehr einsichtig. Denn $1 ist zwar eine Spezialvariable, aber $_ nicht. Und wenn $_ ein Alias auf $1 ist, sollte das mit einem local() eigentlich aufhebbar sein.

Und das wirklich merkwürdige Verhalten von 5.8.8 kann ich mir auch nicht erklären.

View full thread Tiefe Hash Strukturen aus Config bilden: Und warum while(<FH>) gefährlich ist