in reply to "Useless use of a constant" in grep block?

Hello perlancar,

Tangential observation:

push @ary, "foo" unless grep { $_ eq "foo" } @ary;

I think either the any or the none function in the core List::Util module would be better than grep in this case:

push @ary, "foo" unless any { $_ eq "foo" } @ary; # OR push @ary, "foo" if none { $_ eq "foo" } @ary;

Not only are these clearer (since the reader doesn’t have to work out “what is grep returning here?”), but they’re also more efficient because — unlike grep — they short-circuit as soon as a match is found.

Hope that’s of interest,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: "Useless use of a constant" in grep block?
by perlancar (Hermit) on Jul 31, 2017 at 10:18 UTC

    I'm aware of List::Util's any/none/first. Depending on the size of the list, grep or do { for ... } can be faster than List::Util's offerings because there is no subroutine call and argument passing overhead. Also there's a shortcutting variant of grep using eval { grep { ... and die } ... } idiom. I made a benchmark on this in Bencher::Scenario::PERLANCAR::grep_bool.