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.

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

 

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.

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

 

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

print "@fruits\n";

 

This will print each item in the array.

apple banana orange 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

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

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

 

Running the script will produce the following output.

apple
banana
orange
grapes

 


Add new values to the end of an array (push)

Push can be used to add values to the end of an array. For example, let's say you want to add pinnapple to the @fruits array. You certainly could manually update the array to include pinnapple. However, this only makes sense when your array contains predicable and unchanging values. If your array will contain dynamic data, pushing values to the end of the array is very helpful.

my @fruits = qw(apple banana orange grapes);
push (@fruits, 'pinnapple');

 



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