foreach my $i (keys %spl)
{
print "$i:$spl{$i}\n";
}
The foreach keyword is a loop. Usually we write:
foreach XXX (YYY) { ... }
where YYY is an array or hash. The foreach loop will loop through all elements of the array or hash, and each time it will allow you to access the value of the current element by mentioning XXX. So, XXX is going to be a scalar. So, I should really spell it as $XXX. If you omit $XXX, then you can access the element through $_
Inside the foreach brackets, you can refer to $_ or $XXX, and it will hold the value of an element of your array or hash.
You know, a hash is basically a simple array whose values are used as "pointers" to refer to string values. We can think of them as key-value pairs. So, if you use a foreach loop, then the $_ or scalar $XXX is going to hold the key. And you can get the value that it refers to by writing $HASH_NAME{$_} or $HASH_NAME{$XXX}
For example, the environmental variables are stored in a hash in perl. You can access them by reading $ENV{key}. In the following little example, we sort the hashes by key and then we print the key-value pairs:
foreach (sort keys %ENV)
{
print "$_ : $ENV{$_} \n";
}
We could also write it like this :
foreach my $i (sort keys %ENV)
{
print "$i : $ENV{$i} \n";
}
Here is another simple example. This one creates an array that holds the values: ("Happy" "New" "Year!!" "2020" "is" "here") and then it replaces each one with the word "happy":
my @G = qw(Happy New Year!! 2020 is here);
print "\n $G[0]";
print "\n $G[1]";
print "\n $G[2]";
print "\n $G[3]";
print "\n $G[4]";
print "\n $G[5]";
print "\n-----------";
foreach (@G)
{
$_ = 'happy';
}
print "\n $G[0]";
print "\n $G[1]";
print "\n $G[2]";
print "\n $G[3]";
print "\n $G[4]";
print "\n $G[5]";
|