Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Array confusion.

by Marshall (Canon)
on Feb 15, 2017 at 03:30 UTC ( [id://1182044]=note: print w/replies, xml ) Need Help??


in reply to Array confusion.

I think that the problems of modifying a foreach loop array within the loop have been explained well in other posts.

You said: Trying to reverse the array contents without using the "reverse" function...

I haven't bench marked this, but making a copy of an array is usually a relatively fast operation. I suspect "rotating" an array by decreasing its size by one item and then increasing its size by one item is more "expensive" than making a copy which is then consumed (size decreases at every access).

The basic issue with your code is the use of foreach and modifying the array that foreach is iterating over within the loop.

Consider this simple idea:

use warnings; use strict; use diagnostics; my @arr = ('a'..'z'); print "@arr\n"; my @copy = @arr; while (@copy) #size of @copy is re-evaluated at each iteration { my $ele = pop @copy; print "$ele "; } print "\n"; __END__ Prints: a b c d e f g h i j k l m n o p q r s t u v w x y z z y x w v u t s r q p o n m l k j i h g f e d c b a

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-19 12:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found