Saturday, April 5, 2008

Determine the array size in perl


Share at Facebook

If you need to find the array size/length in Perl, there are few ways. In this post, I'll discuss some array length handling process. I hope you'll enjoy the tips.

First of all, below is the code that will find the size/length of the array.

my @array = qw(1 2 3 4 5 6 7 8);
my $length = @array;
print $length . "\n"; ## Printing the size of array

You can also use it directly the array name, for example

my @array = qw(1 2 3 4 5 6 7 8);
print @array . "\n"; ## Another approach to print size

But my suggestion is not to print the array name directly at print statement. Cause when your array name get inside the double quote, it will print all the content of array separate by space. For example the below code block.

my @array = qw(1 2 3 4 5 6 7 8);
print "@array" . "\n"; ## print all elements of array.

It will output as below on screen. But it will help you to print all the content of array separated by space if you need.

1 2 3 4 5 6 7 8

You can find the size of the array using another approach. For example first find the last index of the array, then add 1 with the last index. It will be the size of the array. Check below example code.

my @array = qw(1 2 3 4 5 6 7 8);
my $heighest_index = $#array + 1;
print $heighest_index . "\n";

Hope this little tutorial will help you to understanding few about array handling. Not that much though.




No comments: