Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: "Useless use of a constant" in grep block?

by Athanasius (Archbishop)
on Jul 30, 2017 at 06:02 UTC ( [id://1196288]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1196288]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2024-04-26 00:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found