vinoth.ree has asked for the wisdom of the Perl Monks concerning the following question:

while(my($key, $value) = each(%hash) ) { print "$key => $value\n"; }
my($key, $value); while(($key, $value) = each(%hash) ) { print "$key => $value\n"; }

What is the different between these two code in case of "my" usage ?

Replies are listed 'Best First'.
Re: Different usage of "my"
by moritz (Cardinal) on Mar 25, 2009 at 14:35 UTC
    In the latter case $key and $value are visible after the while loop, in the former case they are not.
Re: Different usage of "my"
by kennethk (Abbot) on Mar 25, 2009 at 14:37 UTC
    The difference is scoping. In the latter case, the variables $key and $value persist outside the loop, whereas they go out of scope once the loops finishes its last iteration in the former case. For example, the following would be valid syntax for the second case, but not the first:

    my($key, $value); while(($key, $value) = each(%hash) ) { print "$key => $value\n"; } print "The last pair was $key => $value\n";

    It's discussed in For LoopsDeclarations.