Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

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?

Thanks


Comment on Re: Perl Idioms Explained - !!expr
Download Code
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.

    HTH

    _________
    broquaint

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):
    (($expr)?1:'')

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (15)
As of 2015-07-28 19:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (258 votes), past polls