I've always quite liked this idiom, which scales nicely when you've got lots of choices:
my $type = "add";
my $redo = {
add => "wiki_add2",
edit => "wiki_edit2",
delete => "wiki_remove3",
}->{$type}
|| "wiki_noneoftheabove7";
print "With type: $type, we could redo: $redo \n";
Also since Perl 5.10, we've had the given keyword. Unless you're targeting legacy releases of Perl, that's probably your best bet:
my $type = "add";
my $redo;
given ($type) {
when ("add") { $redo = "wiki_add2" }
when ("edit") { $redo = "wiki_edit2" }
when ("remove") { log("REMOVE") and $redo = "wiki_remove2" }
default { $redo = "wiki_noneoftheabove7" }
}
print "With type: $type, we could redo: $redo \n";
In Perl 5.12 onwards, when can be used as a (postfix) statement modifier:
my $type = "add";
my $redo;
given ($type) {
$redo = "wiki_add2" when "add";
$redo = "wiki_edit2" when "edit";
when ("remove") { log("REMOVE") and $redo = "wiki_remove2" }
default { $redo = "wiki_noneoftheabove7" }
}
print "With type: $type, we could redo: $redo \n";
And from Perl 5.14, it gets even better, as given has a useful return value.
my $type = "add";
my $redo = given ($type) {
"wiki_add2" when "add";
"wiki_edit2" when "edit";
when ("remove") { log("REMOVE") and "wiki_remove2" }
default { "wiki_noneoftheabove7" }
};
print "With type: $type, we could redo: $redo \n";
|