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.