"Ted Hopp" <te*@newslate.com> wrote in message news:<bk**********@bob.news.rcn.net>...
Why does the following program print "Undefined!"? Shouldn't the subroutine
leave the value of $x alone? (I can understand it clobbering $_, but $x?)
#!/usr/bin/perl -w
use strict;
sub readZip() {
open FH, '/dev/null';
while (<FH>) { print "Got something!\n"; }
}
my $x = 'hi';
for ($x) { readZip(); }
print "Undefined!\n" unless defined $x;
(I'm using perl 5.6.1)
Thanks,
Ted Hopp
te*@newslate.com
It's not a perl's bug.
for ($x) { readZip(); }
This loop run once, $_ is set to $x, in actually, $_ is an alias of
$x, so if something in the for BLOCK changes $_, $x also changed,
while, now look at your readZip.
while(<FH>) { print "Got something!\n"; }
The loop's BLOCK doesn't run, but <FH> is evaluted once. while(<FH>)
is same as
while($_=<FH>), so, $_ is set to undef, and, the outer $x is set to
undef. That's it.
If you change your while statement to something like:
while(my $line = <FH> ) { .. }
everything is OK.