New and Useful Syntax

This section describes Perl statements that have no C or C++ counterpart and are useful besides.

The foreach Statement

Chapter 3, “Arrays,” used the following statement to go through all the elements of an array:

for ($index = 0; $index <= $#array; $index++) 
{ my $element = $array[$index]; }

The same statement can be written more easily as a foreach statement:

foreach $element (@array)

The foreach statement loops through each element in the list. The variable $element is assigned the value of each element as Perl goes through the list.

For example:

my @array = (qw(One Two Three)); 

print "The array contains "; 
foreach my $element (@array) {
    print "$element "; 
} 
print "\n";

This code fragment prints the elements of the ...

Get Perl for C Programmers 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.