in reply to Re^2: accessing variable vaule outside for loop
in thread accessing variable vaule outside for loop

In Perl arrays, the index '-1' accesses the last element in the array. '-2' accesses the second-to-last. ...and so on, down to '- scalar @array', which will be the same element as '$array[0]'.

This makes it easy to simultaneously count upward and downward; just do a numeric negation of sign, and adjust for off-by-one.

@numbers = ( 100, 200, 300, 400, 500 ); $reversed[$_-1] = $numbers[-$_] for 1 .. @numbers; print "$_\n" for @reversed;

Here's just about the only useful use of $[ (which should be avoided, even here).

@numbers = ( 100, 200, 300, 400, 500 ); { no warnings 'deprecated'; local $[ = 1; # Don't do this... example only. $reversed[$_] = $numbers[-$_] for 1 .. @numbers; } print "$_\n" for @reversed;

Dave

Replies are listed 'Best First'.
Re^4: accessing variable vaule outside for loop
by AnomalousMonk (Archbishop) on Jul 07, 2013 at 00:59 UTC

    The array index negate-adjust trick (easily encapsulated in a subroutine) is particularly useful when dealing with 'large' arrays, the reversed elements of which can then be accessed in-place: no reversed copy, possibly quite expensive in terms of space, need be made.