Evan Panagiotopoulos wrote:
>
> I am trying to learn the foreach loop. Is there a place on the web where there are
>examples for the foreach? Basically I have an array of X elements and I > want to go
>from the first element (is it zero?)
Yes!
> to the last. I have a variable containing the number of elements in the array.
>
This can also be obtained from the array itself.
You've got an arrary of 22 elements (@array) - the last index will be
$#array (ie 21)
But you don't *need* to know this for a foreach.
foreach my $num (@array) {
# do somthing with $num
}
Alternatively......
foreach (@array) {
# do something with $_
}
If you *needed* to know the index for each element, you'd probably need
a for loop.
for (my $i = 0; $i<=$#array; $i++) {
# do something with $array[$i]
}
If you wanted to preserve @array, and make a @new_array, use map - a bit
more convenient than a foreach ... { push .... }
my @new_array = map #do something with $_ here#, @array;
eg:
my @new_array = map $_*2 , @array;
Would give 0,2,4,6,8,10,12,14,16.....42,44
--
David Wood, Web Developer
[a] Clickmusic Ltd, 99c Talbot Road, Notting Hill, London W11 2AT
[t] 020 7727 7500
[w] www.clickmusic.co.uk
"There are three types of people in the world; those who can count, and
those who can't."