Arrays in Perl

Home > Search
  by

An array in created by using the @ character. In this example, an array named fruit contains different types of fruit.

@fruits = ("apple", "banana", "orange", "grapes");

 

Instead of placing values in the array, varialbes can be used.

@fruits = ("$citrus", "$berries", "$dry", "$fleshy");

 

Instead of placing quotes around each items in the array, the qw (quote words) function can be used. This also has the added benefit of not having to separate the data with commas. However, this cannot be used with variables in the array.

@fruits = qw(apple banana orange grapes);

 

The print command can then be used to print each item in the array.

print @fruits;

 

This will print each item in the array.

apple banana orange grapes

 


Dumper

Dumper can be used to verify that each item in the array is a unique value. You first need to tell your Perl script to use Dumper.

use Data::Dumper;

 

You can then use print the Dumper output of an array.

print Dumper @fruits;

 

In this example, each piece of fruit is a uniqe value in the array.

$VAR1 = 'apple';
$VAR2 = 'banana';
$VAR3 = 'orange';
$VAR4 = 'grapes';

 


For each loop

foreach loop can be used to loop through a loop through an array. In this example, a foreach loop prints each piece of fruit in the array.

#!/usr/bin/perl

@fruits = qw(apple banana orange grapes);

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

 

Running the script will produce the following output.

apple
banana
orange
grapes

 


Creating an array in a foreach loop

Let's say you want to create arrays inside of the for each loop. In this example, the @afruit array will contain fruit that begins with the letter "a", and the @bfruit array will contain fruit that begins with the letter "b".

#!/usr/bin/perl

@fruits = qw(apple banana orange grapes);
@afruit;
@bfruit;

foreach $fruit (@fruits) {
    print "$fruit\n";

    if ($fruit =~ /^a/) {
      @afruit = $fruit
    }

    if ($fruit =~ /^b/) {
      @bfruit = $fruit
    }
}

print "@afruit \n";
print "@bfruit \n";

 

Running the script will produce the following output.

apple
banana

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments