Friday, April 07, 2006

Perl : Arrays in perl

Creation of arrays

Following statements create perl arrays.

my @fruits = ("apples","bananas","mangoes","grapes");
my @numbers = (23, 42, 69);
my @mixed   = ("bananas", 4.2, 25);

Creating arrays from other arrays.

my @new_fruits = @fruits[1..3]

This cerates a new array which has "bananas","mangoes" and "grapes" of @fruits. This is called an array slice.
Some more ways ...

my @new_fruits = @fruits[1..$#fruits]

$# is a special variable which gives the last index of an array.

my @new_fruits = @fruits[1,2]
creates array of 2nd and 3rd element of @fruits.

Looping through arrays

$\="\n";
for (1..12){
print;
}

Probably the simplest form to understand. You can set a range with '..'
No argument is provided to 'print' so it takes the default input to the loop.
$\ is the output field separator. In our case, it's a newline. Alternatively, (without the first line) we could have written the print statement as follows.

print "$_\n";

$_ is the default input. As in the first case, perl assumes the default input '$_' as an argument to print (and other) statements if not mentioned explicitly.

The following code prints the locations of the perl modules on your system. @INC is the predefined perl array.

for (@INC){
print "$_\n";
}

If used in scalar context, @fruits gives the number of elements in @fruits (array).
e.g.

$x = @fruits;
print $x;

This prints 4 (number of elements in the array).

Some more on perl arrays will be posted here soon. Stay tuned !

No comments: