Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: foreach loops

by Bilbo (Pilgrim)
on May 27, 2002 at 13:51 UTC ( [id://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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (2)
As of 2024-04-24 23:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found