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
In reply to Re^3: accessing variable vaule outside for loop
by davido
in thread accessing variable vaule outside for loop
by gaurav
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |