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

I want to do it without using any predefine function

  • Comment on Re^2: accessing variable vaule outside for loop

Replies are listed 'Best First'.
Re^3: accessing variable vaule outside for loop
by davido (Cardinal) on Jul 06, 2013 at 15:19 UTC

    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

      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.

Re^3: accessing variable vaule outside for loop
by AnomalousMonk (Archbishop) on Jul 07, 2013 at 00:50 UTC
    I want to do it without using any predefine function

    I.e., "This is homework".

Re^3: accessing variable vaule outside for loop
by Anonymous Monk on Jul 06, 2013 at 11:31 UTC

    try the push function to add an element to an array.