On Mon, Feb 25, 2002 at 07:45:30PM +0100, Birgit Kellner wrote:
> for (@array) { # contains a bunch of numbers
> my %hash = &get_record($_);
> }
> foreach (@array) { print "$_\n";\ # problem - $_ is not the array element anymore
It isn't?
$\ = "\n";
my @array = qw(foo bar baz qux);
for (@array) { print }
foreach (@array) { print }
prints:
foo
bar
baz
qux
foo
bar
baz
qux
Are you under the mistaken impression that 'for' is not identical to
'foreach' in everything but name?
Did you expect the $_ from the first loop to carry over into the second? If
so, why? To answer the subject line's question, the foreach loop's iterator
variable is localized to the loop. So, for example, the following will
print nothing but a use of uninitialized value warning (assuming -w):
use vars qw($v);
foreach $v (qw(foo bar baz qux)) { }
print $v;
It works the same for $_.
Even if this weren't true, the second loop reuses $_, effectively
overwriting the initial value. That you didn't see that leads me to believe
you think 'for' is different from 'foreach'; they are the same.
See the foreach documentation in perldoc perlsyn.
Michael
--
Administrator www.shoebox.net
Programmer, System Administrator www.gallanttech.com
--
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]