From: Tony on
Peng Yu <pengyu.ut(a)gmail.com> writes:

> I'm wondering what is the shortest code to count the number of element
> in an array that are greater than some values. I'm just not familiar
> with perl enough to know what is the best way.
>
> A for-loop is the easiest way to think of.
>
> I also come up with the following way. But I'm not sure how to simply
> it in one line. I'm sure that there are better ways. Would you please
> let me know so that I can understand the expressive power of perl?
>
> @new_array=grep { $_ > 5 } @array;
> $#new_array+1

you can just ask for

my $n_greater_than = scalar grep ...;

hth
t
From: J�rgen Exner on
Peng Yu <pengyu.ut(a)gmail.com> wrote:
>I'm wondering what is the shortest code to count the number of element
>in an array that are greater than some values. I'm just not familiar
>with perl enough to know what is the best way.
>
>A for-loop is the easiest way to think of.
>
>I also come up with the following way. But I'm not sure how to simply
>it in one line. I'm sure that there are better ways. Would you please
>let me know so that I can understand the expressive power of perl?
>
>@new_array=grep { $_ > 5 } @array;

Just use the scalar value of the return value of grep:
$count = scalar (grep ......)

>$#new_array+1

Why last array index + 1 instead of simply using @new_array in scalar
context? Using the scalar context is not only easier and cleaner, it is
also correct if someone was crazy enough to modify $[ in which case your
approach would yield the wrong number.

jue
From: J�rgen Exner on
J�rgen Exner <jurgenex(a)hotmail.com> wrote:
>Peng Yu <pengyu.ut(a)gmail.com> wrote:
>>I'm wondering what is the shortest code to count the number of element
>>in an array that are greater than some values. I'm just not familiar
>>with perl enough to know what is the best way.
>>
>>A for-loop is the easiest way to think of.
>>
>>I also come up with the following way. But I'm not sure how to simply
>>it in one line. I'm sure that there are better ways. Would you please
>>let me know so that I can understand the expressive power of perl?
>>
>>@new_array=grep { $_ > 5 } @array;
>
>Just use the scalar value of the return value of grep:
> $count = scalar (grep ......)

Should have mentioned it explicitely: This is of course the manual,
explicit version that you can always use if you can't think anything
smarter.
For grep() itself it is much simpler, just read the documentation of the
function you are using, in particular the last sentence in the second
paragraph.

>>$#new_array+1
>
>Why last array index + 1 instead of simply using @new_array in scalar
>context? Using the scalar context is not only easier and cleaner, it is
>also correct if someone was crazy enough to modify $[ in which case your
>approach would yield the wrong number.
>
>jue