Bootstrap FreeKB - Perl (Scripting) - loop through a range of items in an array
Perl (Scripting) - loop through a range of items in an array

Updated:   |  Perl (Scripting) articles

Let's say you have an array of fruit, like this.

my @fruits = qw(apple banana orange grape peach plum pineapple mango);

 

Each item in the array will have a unique index number, like this.

  • 0 = apple
  • 1 = banana
  • 2 = orange
  • 3 = grape
  • 4 = peach
  • 5 = plum
  • 6 = pineapple
  • 7 = mango

 

By default, a foreach loop will loop through every item in the array, like this.

#!/usr/bin/perl
use strict;
use warnings;

my @fruits = qw(apple banana orange grape peach plum pineapple mango);

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

 

Which will produce the following.

apple banana orange grape peach plum pineapple mango

 

The List::Util module can be used to loop over a range of items in the array. Let's say you want to loop over items 0 through 3. You would do the following.

#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw(min);

my @fruits = qw(apple banana orange grape peach plum pineapple mango);

foreach my $fruit (@fruits[0..min(3,$#fruits)]) {
    print "$fruit ";
}

 

Which will produce the following.

apple banana orange grape

 




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 d8fa73 in the box below so that we can be sure you are a human.