Lots of ways of doing the same thing in Perl - list iteration
Archive - Originally posted on "The Horse's Mouth" - 2012-12-03 08:20:58 - Graham Ellis"There's more than one way of doing it" ... the mantra of Perl, which is both a blessing and a curse. It's a blessing because the programmer has a rich array of tools to hand and can always find a solution, making this ons of the most flexible languages around, and making it quick and easy for the experienced programmer to get to a working model very quickly. But it's a curse because it means that it's too easy to write code that the newcomer finds very hard to follow, or indeed to write code that's hard for anyone to follow later on.
From last week's Perl course - [here] is an example showing five different ways of looping through each member of a list and displaying its contents ... I've shown three flavours of while loop, with different terminator conditions, a for loop using one of those teminations, and a foreach loop which dosn't use the element number at all. Using variations on the same theme, I could have provided two more for loop examples, and three more using foreach rather than for. That's before you start looking at until loops, or do ... while type structures
For the really bizarre, you could also use labelled blocks:
$p = 0;
jumper:
{
print "Have a drink for me in $places[$p]\n";
redo jumper unless (++$p >= scalar @places);
}
And I won't even mention that Perl also has three flavours of goto.
Our Perl courses teach good programming practice as well as the philosophy and techniques of the language. It's our obective to teach you to write code well that's robust and can be easily read and maintained later on.