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 code. (It will probably be you.)
Note
foreach is frequently ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access