in reply to Smartmatch alternatives
My problem with smartmatch is that it tries to replace several more explicit constructs. I prefer to just use the more explicit one, leaving less to heuristics. grep would be fine except for one problem; it does an exhaustive search. There's no (sane) way to tell it to stop searching after the first element meets the search criteria. I don't know if smartmatch stops after the first satisfying condition.
List::Util is a core Perl module. We should consider the functions it offers to be almost as much "first class citizens" as grep. ...except that for documentation we have to look at the module's POD rather than perldoc -f. One of its functions is any. This function stops searching immediately, and returns a true value as soon as one item meets the search criteria. And its name conveys exactly what it does; it's not searching for a whole bunch of things (like grep), it's just going to tell us whether any of the elements meet the criteria.
my $found = any { $_ eq 'something' } @array_of_strings; my $found = any { /\bsomething\b/ } @array_of_strings; my $found = any { $_ == 42 } @array_of_numbers; my $found = any { $_->isa('obj_type') } @array; my $found = any { $_->can('tupitar') } @array;
It's not as succinct as $something ~~ @array, but I can look at it and immediately know the semantics under which $something is being tested, whereas with smartmatch I have to open up perlop and check that my intuition isn't playing tricks on me.
Dave
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Smartmatch alternatives
by tobyink (Canon) on Dec 17, 2013 at 19:22 UTC | |
Re^2: Smartmatch alternatives
by LanX (Saint) on Dec 17, 2013 at 15:56 UTC | |
by davido (Cardinal) on Dec 17, 2013 at 16:05 UTC | |
by Anonymous Monk on Dec 17, 2013 at 16:14 UTC | |
by Laurent_R (Canon) on Dec 17, 2013 at 18:52 UTC | |
by LanX (Saint) on Dec 17, 2013 at 22:37 UTC | |
| |
by davido (Cardinal) on Dec 17, 2013 at 16:19 UTC | |
by tobyink (Canon) on Dec 17, 2013 at 16:29 UTC | |
| |
by LanX (Saint) on Dec 17, 2013 at 16:13 UTC | |
by davido (Cardinal) on Dec 17, 2013 at 16:25 UTC | |
by Anonymous Monk on Dec 17, 2013 at 16:21 UTC | |
by LanX (Saint) on Dec 17, 2013 at 16:50 UTC | |
by tobyink (Canon) on Dec 17, 2013 at 19:01 UTC | |
by LanX (Saint) on Dec 17, 2013 at 22:08 UTC | |
by LanX (Saint) on Dec 17, 2013 at 22:57 UTC | |
|