Perl has these two statements for a reason and they are appropriate each in different cases. When I first learned how to use foreach I was astounded how groovy and useful it can be.
The for command is great for performing a single series of mathematical calculations on a continous and possibly contiguous list of numbers, for example. I don't use it a great deal because what you used to do in BASIC with ...
for i = 1 to 10
myarray(i) = myarray(i) + 1
next i
Or equivalently in Perl...
my $i;
my @array = (1, 5, 6, 9, 57);
for ($i=0; $i <= (scalar(@array)-1); ++$i)
{
++$array[$i];
}
...is done far more easily (and efficiently?) with foreach.
foreach $bar(@bar)
{
++$bar;
}
Basically, foreach allows you to act over a data structure and perform a function efficiently, whereas for allow you to work over a fixed range of numbers with a function (and then presumably do something with the result) or perform a function a given number of times.
Okay, now for the lecture part: Finding this sort of information isn't too difficult, a good start would have been typing 'For loops' and 'Foreach loops' in the search box at the top left of most/all pages on Perlmonks. Don't sweat it, we've all done it at some point and I doubt anyone here will flame you to a crisp but try and give it a go yourself first, play with Perl. Ideally if you are having problems make the title descriptive and then post some example code (inside <code> </code> tags to make it purty) and ask for help: we promise we won't laugh, at least they haven't laughed at me yet!
See this tutorial and this tutorial for help.
Elgon
Update: In response to enlightened posters such as salvadors and turnstep, I am aware of Perl's ability to do 'the right thing' and the fact that in many ways for and foreach are identical, however in it is easier to read and therefore generally 'better style' to use these two commands appropriately. The `efficiently?` comment should be read in backticks to invite answers by people who know more about how Perl works at the lower levels than me.
On a final note, thankyou to merlyn for explaining what I was trying to get across, only better. |