msgbartop
Just another WordPress site
msgbarbottom

12 Nov 08 Perl Array Basics

Initialising or clearing an array

To create a new array it is as simple as declaring it as shown below. This method can also be used to clear an existing array, though you will have to drop the my.

my @array = ();

Creating an array with predefined elements

To create a new array with elements just declare the array with a comma delimited list in brackets after it.

my @array = (hendrix,santana,young,clapton);

Adding elements to the end of an array with push()

In this example we will add new elements to an array using the push() function. To do this we will use a loop to push elements from an existing array @array into our new array cleverly named…@newarray. The variable $item represents the value of the currently accessed element in @array

my @array = (hendrix,santana,young,clapton);
my @newarray = ();
foreach my $item (@array) {
  push( @newarray,$item);
}

Leave a Comment