An array variable starts with an @
in PERL, while a scalar variable begins with a $
. We have to manipulate the array to get its size. This can be done using either of the following two ways:
Let's take a look at these.
We can get the size of an array by simply assigning a scalar variable to the array, and the variable will hold the size of the given array. This process is called implicit scalar conversion.
Let's see how this looks like in the code example below.
In the above code snippet, we do the following:
nums
.nums
by assigning the scalar variable length
to the array nums
.length
, which holds the size of the array nums
.We can get the size of an array by using the scalar context of the array. We can simply achieve this by adding the scalar
keyword while printing the array. Explicitly telling our program to print the scalar value is called explicit scalar conversion.
We can see it working in the code below:
# given array@nums = (10,22,39,44);#display the size of the arrayprint scalar @nums;
In the above code snippet, we do the following:
nums
.nums
, which is returned by scalar @nums
.