Tanktalus has asked for the wisdom of the Perl Monks concerning the following question:
At the end of List::Util's POD is a list of functions that the author, the ever-prolific Graham Barr, has decided are too trivial to include. The first example is:
I don't see that quite as useful as:# One argument is true sub any { $_ && return 1 for @_; 0 }
The reason is that the original means you have to map your list to true/false values before using any while the latter means you can evaluate each one until you find the one you're interested in.sub any(&@) { my $code = shift; $code->() && return 1 for @_; 0 }
The observant may notice that this is exactly the same as first - but the extremely observant will notice that it is merely almost the same as first. To whit:
This will set $has_undefs to undef no matter what. However, substitute first for any (my version of any, not Graham's), and now it will return true if any element of @list is undef.my $has_undefs = first { not defined } @list;
Similar changes could be made to all, notall, and none. The true and false (counting) functions, however, I don't see such a change required simply because the underlying code is already generic. Having a function named "count" like this:
doesn't seem to give you much. Calling count { blah() } @list vs scalar grep { blah() } @list doesn't seem significant.sub count(&@) { my $code = shift; scalar grep { $code->() } @_ }
Since I've noticed Graham's contributions to perl are somewhat larger than my own, I'm going to make the assumption that I'm missing something, not him. Thus, I'd appreciate if anyone could enlighten me as to what I'm missing. ;-)
PS - I've used this code in Template::Plugin::ByDate which is my own answer to a previous post here. So, if I'm missing something, the sooner I know, the better. :-)
Update: As borisz points out, List::MoreUtils has what I was looking for. I had completely forgotten about that. Thanks, borisz! I've installed that and updated my code to use it.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: List::Util's any function
by borisz (Canon) on Apr 25, 2006 at 17:47 UTC | |
|
Re: List::Util's any function
by diotalevi (Canon) on Apr 25, 2006 at 16:02 UTC | |
by eric256 (Parson) on Apr 25, 2006 at 17:03 UTC |