matthew has asked for the wisdom of the Perl Monks concerning the following question:
So I was writing up a post about why a particular while statement was not getting executed while (forgive the pun) an equivalent foreach loop was when I realized my mistake.
I was operating with a scalar value not a list. Which led me to peer furthur into the depths of foreach, out of curiosity...
Prints:my $scalar; foreach ($scalar) { print "\$scalar = $_\n"; } print "_END_\n";
$scalar = _END_
Prints: _END_my @array foreach (@array) { print "\$array[x] = $_\n"; } print "_END_\n";
Prints:my @array $array[0] = ""; foreach (@array) { print "\$array[x] = $_\n"; } print "_END_\n";
$array[x] = _END_
It starts to make sense (kind of) when you add another element...
# foreach operating on an array with two elements. first element defined as empty:Prints:my @array $array[0] = ""; $array[1] = "foo"; foreach (@array) { print "\$array[x] = $_\n"; } print "_END_\n";
$array[x] = $array[x] = foo _END_
Thought it might be of interest...
-Matthew
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
RE: While Vs. Foreach
by mikfire (Deacon) on Jul 18, 2000 at 22:03 UTC |