When I would print out $_, or in this case, $i, instead of giving me the actual data, I get the index of the array. How would I print out, and use, the actual data in the array? Would using a C-style $array_scalar = $array[$i] work, or is this syntax not supported in Perl?
Sigh. How hard can it be to type that into your script and TRY IT?
BTW: The usual way to filter lists (including arrays) is to use grep if you want a list of all matching elements. E.g. to get a list of all even numbers in the range from 1 to 10:
>perl -E 'say for grep { $_%2==0 } (1..10)'
2
4
6
8
10
>
(On Windows, use double quotes instead of single quotes.)
List::Util can do more:
What is the FIRST even number in that range?
>perl -E 'use List::Util qw( first ); say first { $_%2==0 } (1..10)'
2
>
Are there ANY even numbers in that range?
>perl -E 'use List::Util qw( any ); say any { $_%2==0 } (1..10)'
1
>
(any() returns a boolean value, so 1 means "yes", not "there is only one even number")
Are ALL numbers in that range even?
>perl -E 'use List::Util qw( all ); say all { $_%2==0 } (1..10)'
>
(Again a boolean result, an empty string or undefined value. Both are false, telling you that the range contains numbers that are not even.)
What's the SUM of all even numbers in that range?
>perl -E 'use List::Util qw( sum ); say sum grep { $_%2==0 } (1..10)'
30
>
And so on ...
Hint: List::MoreUtils knows even more tricks.
Alexander
--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
|