Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: accessing variable vaule outside for loop

by eyepopslikeamosquito (Canon)
on Jul 06, 2013 at 11:07 UTC ( #1042884=note: print w/ replies, xml ) Need Help??


in reply to accessing variable vaule outside for loop

If your intent is to reverse the @number array, why not write it like this?

my @number = (1,2,3,4); my @rev = reverse @number; print "@rev\n";
See reverse. If that is not your intent, please clarify.


Comment on Re: accessing variable vaule outside for loop
Select or Download Code
Re^2: accessing variable vaule outside for loop
by gaurav (Acolyte) on Jul 06, 2013 at 11:26 UTC

    I want to do it without using any predefine function

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

      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.

      I want to do it without using any predefine function

      I.e., "This is homework".

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1042884]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (8)
As of 2014-12-29 15:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (192 votes), past polls