Perl has about 5 billion things it can do too, but many of them are built into the nuances of its rich syntax, some are functions, some are functions evaluated in various contexts, and others are brought to you by virtue of pragmas and core modules. Of course CPAN is a whole other chapter in the book... but I digress...
An array, evaluated in scalar context, will return its number of elements. Therefore:
my @array = qw/one two three four five/; print scalar @array; __OUTPUT__ 5
There are a few other tricks you can do with arrays too...
my @array = qw/one two three four five/; print $#array; __OUTPUT__ 4
Explanation: Arrays start with the sigil @. @array, for example, is an array. And if @array is an array, $#array is a special syntax used to determine the index of the last element of an array. If @array has five elements, and you start counting from zero (the index of the first element), the index of the last element is 4. And that's the number you get when you evaluate $#array.
my @array = qw/one two three four five/; $array[2] = undef; # undefine one of the elements. print scalar grep { defined $_ } @array; __OUTPUT__ 4
Here you're using grep in scalar context to count how many elements in @array actually contain a value. There are five elements in @array, the last index is 4, and because we've erased the contents of $array[2], despite there being five elements, only four of them hold a value, so the output is 4.
my @array = qw/one two three four five/; print $array[-1]; __OUTPUT__ five
Here you're indexing into @array, but asking for the element with the index of -1. When you ask for negative indices, Perl starts at the end of the array and counts backwards. So in a five element array, $array[4] (the fifth element) is the same thing as $array[-1] (still the fifth element).
my @array = qw/one two three four five/; $#array = 99; print scalar @array; __OUTPUT__ 100
Huh? What you've just done here is pre-extend the five element array named @array out to one hundred elements (95 of them just contain 'undef' (no value)).
Perlish arrays are also easily usable as FIFO queues, LIFO stacks, double-ended stacks, and so on, via push, pop, shift, unshift. ...oh, and don't forget splice.
Just wanted to offer a few tidbits of Perl's rich syntax and a few functions that expand the horizons of that syntax. Most of this isn't immediately helpful to your question, but just demonstrates a few other very useful tricks.
Enjoy.
Dave
In reply to Re: perl equivalent to php array count function
by davido
in thread perl equivalent to php array count function
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |