Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Short form (ternary) if else

by Riales (Hermit)
on Feb 08, 2012 at 19:59 UTC ( #952570=note: print w/ replies, xml ) Need Help??


in reply to Short form (ternary) if else

I think what you're looking for is this:

my $vxdg = exists $vxdg{$node}{$disk} ? $vxdg{$node}{$disk} : '';
Also, in your if/else statement, if you declare $vxdg inside the if/else like you are doing, it goes out of scope by the time you get out of the if/else block.


Comment on Re: Short form (ternary) if else
Select or Download Code
Re^2: Short form (ternary) if else
by gg48gg (Sexton) on Feb 08, 2012 at 20:29 UTC
    Yes, that works beautifully! Thank you! I realize the scope issue as well. So, what I understand is that ternary form is only for use after an assignment (=) operator? Is that correct?

      No, it doesn't have to be used in conjunction with assignment. Consider:

      printf("X is %s\n", defined $X ? $X : 'undefined');

      Or:

      sub get_name { # ... return wantarray ? ($firstname, $middlename, $lastname) : "$firstname $lastname"; }

      Yes and no... It is typically at it's most useful after an assignment, and it's use is that it generates a value, but that doesn't necessarily mean it needs to be used in an assignment. Others have given examples, but the essential thing to remember is that the ternary operator returns a value. if does not: It is a flow-control operator.

      So, where it does need to be used is where Perl would expect a value. Assignments are one common case of that.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (5)
As of 2015-07-06 03:16 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 (69 votes), past polls