Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Return value in ternary

by Anonymous Monk
on Mar 29, 2010 at 16:07 UTC ( [id://831651]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

Can you have a ternary in 'return'?
my $flag = 'yes'; my $return_value = test($flag); # return 'yes' $flag = ''; $return_value = test($flag); # return 'none' sub test() { my $value = shift; return $value ? $value : 'none'; # is the above line valid? }

Thank you :)

Replies are listed 'Best First'.
Re: Return value in ternary
by ikegami (Patriarch) on Mar 29, 2010 at 16:33 UTC

    I'm not sure why you asking this since your code clearly demonstrates that it does work. return accepts any expression. The only question might be one of precedence.

    Does return $value ? $value : 'none'; mean return ( $value ? $value : 'none' ); or ( return $value ) ? $value : 'none'; ?

    If you're not sure of the precedence, a simple test will tell you. (Again, you already did that, so I don't know why you are asking.) Either way, you can state the precedence you desire explicitly using parens.

Re: Return value in ternary
by JavaFan (Canon) on Mar 29, 2010 at 16:37 UTC
    # is the above line valid?
    Is it really easier to compose a post, then to just run the code and see if the compiler throws an error?
Re: Return value in ternary
by toolic (Bishop) on Mar 29, 2010 at 16:16 UTC
Re: Return value in ternary
by ramlight (Friar) on Mar 29, 2010 at 16:13 UTC
    Yes, you can return undef as well as a value. You would need to do a defined test in order to differentiate between undef and false.
Re: Return value in ternary
by Anonymous Monk on Mar 30, 2010 at 14:18 UTC

    Thanks all :)

    I ran the code before posting. Though I got the result I expected, I wasn't sure whether it was valid perl code in the sense of whether people would actually write it that way.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2024-04-17 09:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found