foreach

The foreach construct performs a statement block for each element in a list or array:

@names = ("alpha","bravo","Charlie");foreach $name (@names) {  print "$name sounding off!\n";}

The loop variable ($name in the example) is not merely set to the value of the array elements; it is aliased to that element. That means if you modify the loop variable, you’re actually modifying the array. If no loop array is specified, the Perl default variable $_ may be used:

@names = ("alpha","bravo","Charlie");foreach (@names) {  print "$_ sounding off!\n";}

This syntax can be very convenient, but it can also lead to unreadable code. Give a thought to the poor person who’ll be maintaining your ...

Get Ubuntu Unleashed 2014 Edition: Covering 13.10 and 14.04,Ninth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.