Top 5ways to get Array size in Perl with Code (examples)
The array contains a list of elements unordered.
Sometimes, you need to find the number of elements i.e. size. This post talks about multiple ways to know the size of an array in Perl with code examples.
Perl Array length examples
Perl allows us to use an array in a list and scalar context.
In List Content, Array returns the list of elements. Scalar Context, Array return size of an element
- using scalar keyword
Print an array using scalar context as given below
@numbers = (11, 22, 33,44,55,66);
print scalar @numbers
- Last Index syntax(
$#array
)
$#array
return last index of an array. If the array contains 5 elements, the $#array
returns 4. So adding 1 to this returns the size of an array.
@numbers = (11, 22, 33,44,55,66);
print $#numbers+1;
- using smart match operator Perl 5.18 introduced a smart match operator (
~~
) in the experimental feature.
So you have to use the below line to use this feature in your code.
use experimental 'smartmatch';
printing variable with smartmatch returns the size of an array.
use warnings;
use experimental 'smartmatch';
@numbers = (11, 22, 33,44,55,66);
print 0+@numbers;
print ~~@numbers
- using scalar context,
Create a scalar context by assigning an array to a variable. Print the array
@numbers = (11, 22, 33,44,55,66);
## Create a scalar context
my $count = @numbers;
print $count;
How do I determine the size of an array in Perl?
To print an array size in Perl, Please follow the below steps
- Use array variables in scalar content in multiple ways
- The first way, print using the scalar keyword of an array variable
print scalar @array
- second, Create a scalar context by assigning an array variable to the scalar variable
@numbers = (11, 22, 33,44,55,66);
## Create a scalar context
my $count = @numbers;
print $count;
- It returns several elements in an array.
Which function is used to find the length of an array in Perl?
Perl allows list and scalar context, List only returns elements, and scalar returns the size of elements. So, Scalar
function is used to find the length of an array in Perl
What is a scalar array in Perl?
The scalar array is an array of scalar or mixed typed values in Perl. Scalar value contains strings, integers, and floating numbers. For example, the array declared as given below.
@numbers = (11, 22, 33,44,55,66);