Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: accessing variable vaule outside for loop

by eyepopslikeamosquito (Chancellor)
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
Replies are listed 'Best First'.
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

      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".

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

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 studying the Monastery: (17)
As of 2015-07-30 19:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (273 votes), past polls