Switch

Believe it or not, until version 5.8 Perl had no switch. And even now switch is not a core part of the language. How could perl programmers do without it? Emulation is the answer.

We ask a numeric value to the user, there are many possible branches we can take accordingly to the passed value, so the natural way of designing the code would be through a switch. In perl (pre 5.8) we could emulate it in this way:

print "Enter 1 or 2: ";
my $value = <>;
for($value) {
$_ == 1 && do { print "one\n"; last; };
$_ == 2 && do { print "two\n"; last; };
print "unexpected\n";
}

Notice the last statement in the do block. If we didn't write it, the "default" would have been executed by any branch.

From Perl version 5.8 we can use a real switch. For our simple problem this a possible solution:

use Switch;

switch($value) {
case 1 { print "one\n" }
case 2 { print "two\n" }
else { print "unexpected\n" }
}

No comments:

Post a Comment