The foreach statement is a core Perl idiom. The foreach command executes a block of code for a set of scalars, as might be stored in a list.
For example the next code fragment checks that everybody produced their last homework.
foreach $user (@users) { if (-e ``/home/$user/public_html/cgi-bin/hello_world.pl''){ print ``Looks like $user did their homework\n''; } else { print ``Looks like $user did not do their homework\n''; } }
In this code the array ``@users'' contains a list of user names and the operator ``-e'' checks to see if a file exists. The scalar $user is assigned each element of the list in turn, which is then used in the loop.
One way of iterating over a hash is as follows:
foreach $key (keys %letters){ print ``The value of $key is $letters{$key} \n''; }