Bootstrap FreeKB - Perl (Scripting) - foreach loops
Perl (Scripting) - foreach loops

Updated:   |  Perl (Scripting) articles

A foreach loop can be used to loop through a loop through an array. For example, let's say there is an array of fruit.

my @fruits = qw(apple banana orange grapes);

 

In this example, a foreach loop prints each piece of fruit in the array.

#!/usr/bin/perl

use strict;
use warnings;

my @fruits = qw(apple banana orange grapes);

foreach my $fruit (@fruits) {
    print "$fruit ";
}

 

Running the script will produce the following output.

apple banana orange grapes

 


Loop through hash

Let's say you have the following hash of key value pairs.

%food = ('fruit',banana,'vegetable',onion,'grain',bread);

 

The following foreach loop will print the keys.

foreach my $key (keys %food) {
    print $key;
}

 

This will print the keys.

fruit
vegetable
grain

 

The following foreach loop with print the values.

foreach my $value (values %food) {
    print $value;
}

 

This will print the values.

banana
onion
bread

 

Or like this, to loop through both the keys and the values.

foreach my $key (keys %food) {
  foreach my $value ($hash{$key}) {
    print "$key -> $value\n";
}

 

Will print the following.

fruit -> banana
vegetable -> onion
grain -> bread

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 6b4203 in the box below so that we can be sure you are a human.