At 10:46 AM 7/13/2005, Thomas, Mark - BLS CTR wrote:
John Deighan wrote:
> We have a goto in our code. I hate it, but there just isn't a good
"switch" or "case" statement in Perl yet
Yes there is, in Perl 5.8. If you're using an older Perl, you can still get
Switch.pm from CPAN.
Great to know, but... What I see below looks semantically great - regular
expressions and all that. However, that tells me that each case needs to be
tried to find the matching case, which can be computationally very
expensive, especially if there are hundreds of cases. What we need is a
single (usually hash algorithm) lookup that determines very quickly the
case that applies. That's what a "case" statement in Pascal (and, I think,
a "switch" in C) does. That is also what a "goto $op" does in Perl, where
$op must be the name of an existing label.
One possibility is that Perl might check if every case value is a scalar,
and generate the more efficient hash lookup method in that case. That would
be great since it would basically optimize to the best method depending on
the complexity of the case values, but I don't know if it does that. But,
in our case, we definitely need the switch to be as efficient as possible.
use Switch;
switch ($val) {
case 1 { print "number 1" }
case "a" { print "string a" }
case [1..10,42] { print "number in list" }
case (@array) { print "number in list" }
case /\w+/ { print "pattern" }
case qr/\w+/ { print "pattern" }
case (%hash) { print "entry in hash" }
case (\%hash) { print "entry in hash" }
case (\&sub) { print "arg to subroutine" }
else { print "previous case not true" }
}
Scanned for Spam and Viruses.
_______________________________________________
Perl-Win32-Users mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs