Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re: wantarray alternative

by Preceptor (Deacon)
on Jul 10, 2013 at 18:36 UTC ( #1043531=note: print w/replies, xml ) Need Help??

in reply to wantarray alternative

#include disclaimer on why one-liners are generally undesirable.

Consider a ternary operator. Specifically:

condition ? result_if_true : result_if_false

You could then make this function:

wantarray ? first {$_} map { lc } @_ : map { lc } @_ ;

Note also - return is (almost) redundant if it's the last line of the code - by default Perl returns from a sub 'the result of the last operation'. This too though, isn't always a good thing, because readable code almost always trumps really short code.

Replies are listed 'Best First'.
Re^2: wantarray alternative
by Your Mother (Bishop) on Jul 10, 2013 at 18:50 UTC
    readable code almost always trumps really short code

    I know what you're saying but shorter code, like shorter sentences, tends to be more readable; short != confusing|obfuscated. Omitting return is a best practice, to me, when there is no control flow and the sub is short.

Re^2: wantarray alternative
by tqisjim (Beadle) on Jul 10, 2013 at 19:04 UTC

    I did not intend to ask the question How do I use the tertiary operator?. Both these answers rely on the trivial lc operation I used in my example.

    To rephrase: What's the most elegant way to modify the default behavior of a subroutine that returns a list of one?

    sub lowercase { my @out = map { lc } @_ ; return wantarray ? map { $_ } @out : first { $_ } @out ; }

    So my specific question is: How can I move the operation from the first line into the second line to avoid using the place holder out?

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1043531]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2018-05-21 11:55 GMT
Find Nodes?
    Voting Booth?