http://www.perlmonks.org?node_id=374289


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

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:'')