Tuesday, April 7, 2009

Perl: Access multiple values of Array

Share at Facebook

Hi guys, you must know how to access the array of Perl using index. its easy. Just use like other language. But I'm going to give you an example about accessing a Perl array for multiple index at the same time. Lets say we have an array as below.

## this is the initial array
@my_array = qw(mango banana orange apple coconut strawberry papaya);

We can easily access a single element from the array as like other languages. But still here it is. It will print banana from the array

## printing a single elements
print $my_array[1];

Now, lets access three elements from the Perl array at the same time using different indexes. At below code, you can easily see that I'm accessing the array for 2nd 5th and 1st position. It will print orange,strawberry,banana on the screen

## get the second, fifth, and first elements from the array
@new_array = @my_array[2,5,1];
print join(",", @new_array);

You can use your double dot(..) operator to access as from-to, i mean from 1 to 5 as an example. At below code, it will print the 33 to 5th index from the array. It will output apple,coconut,strawberry on scree.

## get the third, fourth, and fifth elements from array
@new_array = @my_array[3..5];
print join(",", @new_array);

Also you can use, get from 3-5 and 1st element from array. For example below code will output apple,coconut,strawberry,banana from the array
## get the third, fourth, fifth, and 1st elements from array
@new_array = @my_array[3..5,1];
print join(",", @new_array);

Also you can use the same index value multiple times to access the same value. For example at below code, it will access the 2nd elements from the array 4 times, and will get orange four times on screen.

## get only the 2nd element from the array 4 times
@new_array = @my_array[2,2,2,2];
print join(",", @new_array);

That's all about to accessing an array of Perl using multiple index at the same time. Do you know any other way to do this at Perl?

1 comment:

vuvie said...

great resource here, thanks!