Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: Perl Idioms Explained - !!expr

by Anonymous Monk
on Jul 14, 2004 at 13:09 UTC ( #374289=note: print w/replies, xml ) Need Help??

in reply to Perl Idioms Explained - !!expr

Can you comment on the alternatives?

return grep { $_ eq $_[0] } @_[ 1 .. $#_ ]; # or return ~~grep { $_ eq $_[0] } @_[ 1 .. $#_ ]; # or my $searched = shift; return !!grep { $_ eq $earched } @_;

Should I use them? And if not, why?


Replies are listed 'Best First'.
Re^2: Perl Idioms Explained - !!expr
by broquaint (Abbot) on Jul 14, 2004 at 13:17 UTC
    return grep { $_ eq $_[0] } @_[ 1 .. $#_ ];
    Depending on context this will return different things, whereas !!expr will always return a boolean value.
    return ~~grep { $_ eq $_[0] } @_[ 1 .. $#_ ];
    This will return the number of elements returned by grep as opposed to !!expr which, again, will return a boolean value.

    Of course both of the above are valid in appropriate situations, but if you just want a boolean value then !!expr is an appropriate idiomatic solution.



Re^2: Perl Idioms Explained - !!expr
by japhy (Canon) on Jul 14, 2004 at 14:46 UTC
    I like ~~EXPR as a brief (read: obfuscated) way to enforce scalar context on an expression; it only renders the return value unusable if EXPR is a reference.
    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re^2: Perl Idioms Explained - !!expr
by davidrw (Prior) on Nov 05, 2005 at 02:55 UTC
    I would also mention just a simple ternary operator as an alternative:
    return grep($_ eq $_[0], @_[ 1 .. $#_ ]) ? 1 : '';
    or, more generally the equivalent to !!$expr is (some of the parens are optional depending on context):

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2021-04-15 15:21 GMT
Find Nodes?
    Voting Booth?

    No recent polls found