просто сделать вещи короче:
sub get_age1 {
my $age = shift;
$age == 1 ? print "do something" :
$age == 2 ? print "do somthing2" :
$age == 3 ? print "do somthing3" :
$age == 4 ? print "do somthing4" :
print "error"
}
это имеет смысл, если условие может быть лучше всего выражено в виде регулярного выражения:
sub get_age2 {
for (shift) {
if (/^ 1 $/x) {print "do something"}
elsif (/^ 2 $/x) {print "do somthing2"}
elsif (/^ 3 $/x) {print "do somthing3"}
elsif (/^ 4 $/x) {print "do somthing4"}
else {print "error" }
}
}
Вот несколько таблиц отправки:1007 *
простой (с ошибкой):
{
my %age = ( # defined at runtime
1 => sub {print "do something"},
2 => sub {print "do somthing2"},
3 => sub {print "do somthing3"},
4 => sub {print "do somthing4"},
);
# unsafe to call get_age3() before sub definition
sub get_age3 {
($age{$_[0]} or sub {print "error"})->()
}
}
лучше:
{
my %age;
BEGIN {
%age = ( # defined at compile time
1 => sub {print "do something"},
2 => sub {print "do somthing2"},
3 => sub {print "do somthing3"},
4 => sub {print "do somthing4"},
)
}
# safe to call get_age4() before sub definition
sub get_age4 {
($age{$_[0]} or sub {print "error"})->()
}
}
другой способ написать это:
BEGIN {
my %age = ( # defined at compile time
1 => sub {print "do something"},
2 => sub {print "do somthing2"},
3 => sub {print "do somthing3"},
4 => sub {print "do somthing4"},
);
# safe to call get_age5() before sub definition
sub get_age5 {
($age{$_[0]} or sub {print "error"})->()
}
}
еще один хороший способ написать это:
{
my $age;
# safe to call get_age6() before sub definition
sub get_age6 {
$age ||= { # defined once when first called
1 => sub {print "do something"},
2 => sub {print "do somthing2"},
3 => sub {print "do somthing3"},
4 => sub {print "do somthing4"},
};
($$age{$_[0]} or sub {print "error"})->()
}
}