in reply to Simple question about foreach and my.

As others have put it, it's a matter of scoping, both are correct for 99.9% of the cases out there. But, as an example of where you'd want to have the my statement elsewhere of the foreach statement:
my $element; foreach $element (@set_of_numbers) { last if $element < $critical_value; } print "$element is below the critical value.\n";
If the my was inside the foreach, $element would not have scope outside the loop, and therefore you'd run into problems with the print statement.
Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain

Replies are listed 'Best First'.
Re: Re: Simple question about foreach and my.
by petral (Curate) on Mar 27, 2001 at 23:39 UTC
    Actually, I don't think that works. The reasoning is that since $_ is local'ed inside foreach loops, any loop variable should be. This is supposedly in support of the principle of "least surprises". Anyway, with 5.05003 I get:
    > perl -lwe '$x=$y=0; foreach $x (0..9) { ++$y } print "$x, $y"' 0, 10 > perl -lwe 'my($x,$y)=(0,0); foreach $x (0..9) { ++$y } print "$x, $y +"' 0, 10 > perl -lwe '$y=0; foreach $x (0..9) { ++$y } print ! defined $x,", $y +"' 1, 10 > perl -lwe 'my $y=0; foreach my $x (0..9) { ++$y } print ! defined $x +,", $y"' Name "main::x" used only once: possible typo at -e line 1. 1, 10 >


    p