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

Re: in search of a more elegant if then else

by FunkyMonk (Chancellor)
on Feb 19, 2010 at 11:10 UTC ( [id://824135]=note: print w/replies, xml ) Need Help??


in reply to in search of a more elegant if then else

As other Monks have suggested, the conditional operator does what you want. They have also pointed out that it can become difficult to read. However, if you set your code out carefully, the conditional operator can produce elegant and easy to read code. Consider:

my $n = 3; my $s = $n == 1 ? 'one' : $n == 2 ? 'two' : $n == 3 ? 'three' : $n == 4 ? 'four' : 'ETOOBIG'; print "$n : $s\n"; # 3 : three

But, in some circumstances, you may be able to use a hash table:

my %h = ( 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four' ); $s = $h{$n} // 'ETOOBIG'; # needs perl 5.10 #$s = $h{$n} || 'ETOOBIG'; # works for any perl print "$n : $s\n"

See perlop for the difference between the or (||) and defined or (//) operators


Unless I state otherwise, all my code runs with strict and warnings

Replies are listed 'Best First'.
Re^2: in search of a more elegant if then else
by doug (Pilgrim) on Feb 19, 2010 at 16:11 UTC

    And with 5.10 there is given/when

    given ( $n ) { when ( 1 ) { $s = 'one'; } when ( 2 ) { $s = 'twe'; } when ( 3 ) { $s = 'three'; } when ( 4 ) { $s = 'four'; } default { $s = 'ETOOBIG'; } }

    - doug

      i should read the changes more, i love this! so simple and easy to understand.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (8)
As of 2024-03-28 09:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found