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

Re: foreach loops

by Bilbo (Pilgrim)
on May 27, 2002 at 13:51 UTC ( #169578=note: print w/replies, xml ) Need Help??

in reply to foreach loops

I think that it would be useful to point out that the loop variable is aliased to each element of the array in turn. It is not a copy of the element, so modifying the loop variable will modify the original array. One simple application of this is the initialisation of an array.
# Initialise an array so that $array[n] = n my $n = 0; foreach (@array) {$_ = $n++}

Replies are listed 'Best First'.
Re: Re: foreach loops
by Hofmator (Curate) on May 27, 2002 at 14:02 UTC
    # Initialise an array so that $array[n] = n my $n = 0; foreach (@array) {$_ = $n++}
    Your code is overwriting the contents of an already existing array, I wouldn't call that initialising ...

    Putting that aside, an array slice is a good way to do that task without using a loop.

    @array[0..100] = 0..100; # or to mimic the behaviour of your code exactly @array[0..$#array] = 0..$#array;

    -- Hofmator

      Thank you - I've suddenly understood what array slices are for and how useful they are (I haven't been learning Perl for very long - I've certainly got a long way to go). I admit that I didn't choose a very good example. I think that my main point is still relevant though.
Re: Re: foreach loops
by bivouac (Beadle) on Dec 03, 2002 at 16:32 UTC
    No one's reading this, but thanks Bilbo. Super help on a problemo I've been having - I think I think too much about the problems I have.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2022-05-19 08:05 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (71 votes). Check out past polls.