in reply to foreach my $var scope oddness

In a foreach loop, the loop variable ($o in this case, $_ if none is specified) is a alias to (not a copy of) the current element of the list over which the loop interates. Any changes to the loop variable is reflected back to the list element.

In other words

foreach my $o (@outer) { $o .= 'loop'; print $o, "\n"; }

is the same as

$outer[0] .= 'loop'; print $outer[0], "\n"; $outer[1] .= 'loop'; print $outer[1], "\n"; $outer[2] .= 'loop'; print $outer[2], "\n";

Update: Switched to terminology that's more appropriate for Perl, as per Grandfather's recommendations.

Replies are listed 'Best First'.
Re^2: foreach my $var scope oddness
by GrandFather (Saint) on May 21, 2006 at 07:14 UTC

    <nitpick>Actually "is an alias to", not "is a reference". The loop variable doesn't get dereferenced to access the current element - it is in essence the current element.</nitpick>

    I find it better to refer to it as the "loop variable" rather than the "index variable". In Perl it is seldom an index and even when it is, it is still the "loop variable" and is aliased to each list item in turn.


    DWIM is Perl's answer to Gödel