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.