Arrays

This page will show different ways to handling arrays and some tricks as well. It is not complete, by far.

An array is a data type in Perl which is basically a list of values you want to store.

my @array = ('apple','flour','cinnamon','suggar','butter');

A very simple way or making an array of 10 elements

my @array = (1..10);

This is similar to:

my @array = (1,2,3,4,5,6,7,8,9,10);

but much shorter.

Another way of making an array of 10 elements, but now all have the same value.

my @array =  (0) x 10;

Now your array will look like (0,0,0,0,0,0,0,0,0,0);

I see this quite often when someone wants to change or do something with each element in an array. I think it is not the most elegant solution, also it is more error prone.

for (my $i = 0; $i < = scalar @array -1; $i++) {
	$array[$i] = 1;
}

Now your array will look like (1,1,1,1,1,1,1,1,1,1);

Many people forget that $#array will give you the same number as “scalar @array -1″. I find this much better readable.

foreach my $i (0..$#array) {
	$array[$i] = 2;
}

Now your array will look like (2,2,2,2,2,2,2,2,2,2);

Or when you only want to manipulate each element in an array, just modify the $_ in a foreach loop!

foreach (@array) {
	$_ = 3;
}

Now your array will look like (3,3,3,3,3,3,3,3,3,3);

You could also consider ‘map’

map { $_ = 4 } @array;

Now your array will look like (4,4,4,4,4,4,4,4,4,4);

Infinitely cycle through each value of an array (make sure you can escape the loop):

while (my $element = shift @array) {
	push @array, $element;
	print "$element\n";
}
  1. No comments yet.
  1. No trackbacks yet.