in reply to in search of a more elegant if then else
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
|
|---|
| 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 | |
by Anonymous Monk on Jan 16, 2011 at 22:31 UTC |