Example six a - foreach structures


# Example six a - FOREACH structures.
# the associative array %a and the array @a are used to exemplify
# the power of FOREACH. The $_ automatic variable is also shown.
#
# by Al Bento

$a = "this is example";
$b = 6;
$a{"field1"} = $a;
$a{"field2"} = $b;

@a = %a;

# see below how easy is printing all elements of the array @a
# using foreach

foreach $g (@a)   {
       print "$g\n"; }

print "\n";

# if you use the automatic (implicit) $_ variable and do not name
# a variable like I did above (I used $g), see how simple it can be

foreach (@a)   {
       print;
}

# foreach is also useful to process associative arrays. The keys()
# operator is also introduced -- keys(%a) returns the key fields
# of the associative array %a. You can omit the parentheses in keys.

print "\n\n";

foreach $k (keys (%a))   {      # another way: foreach $k (keys %a)
       print "$k = $a{$k}\n";
}

download the script


This page is maintained by Al Bento who can be reached at abento@ubmail.ubalt.edu. This page was last updated on February 15, 2001. Although we will attempt to keep this information accurate, we can not guarantee the accuracy of the information provided.