Array Length
You may find the number of elements in the array @days by evaluating @days in scalar context, such as:
@days + 0; # implicitly force @days into scalar context scalar(@days) # explicitly force @days into scalar context
Note that this only works for arrays. It does not work for list values in general. As we mentioned earlier, a comma-separated list evaluated in scalar context returns the last value, like the C comma operator. But because you almost never actually need to know the length of a list in Perl, this is not a problem.
Closely related to the scalar evaluation of @days is $#days. This will return the subscript of
the last element of the array, or one less than the length, since
there is a 0<th> element. Assigning to $#days changes the length of the array.
Shortening an array by this method destroys intervening values. You
can gain some measure of efficiency by preextending an array that is
going to get big. (You can also extend an array by assigning to an
element beyond the end of the array.) You can truncate an array down
to nothing by assigning the null list () to it. The following two statements are
equivalent:
@whatever = (); $#whatever = –1;
And the following is always true:
scalar(@whatever) == $#whatever + 1;
Truncating an array does not recover its memory. You have to
undef(@whatever) (or let it go out of scope) to free its memory back to your process’s memory pool. You probably can’t free it all the way back to your system’s memory pool because few operating ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access