Many languages support a switch/case structure for only evaluating a condition once. Perl has no such official structure, though there are several ways of getting the same idea without it. However, these ways are not as efficent as the "real" switch/case structures you get in C or Java. Larry has said that an offical structure will be added in Perl6, but that doesn't help us right now.
I was inspired by a post by pg, where he made a point about a "switch" structure in the parent node, and another unrelated point about using a hash instead of an array. For some reason, these two seemingly seperate points made by brain click some peices together. Why not use a hash as a switch/case structure, using subroutine referances to execute the actual case? This should give us all the benifits of the single-evaluation of the equivilent C structure. We can even pass arguments into the case.
I've searched around a bit and haven't seen this used before. If anyone knows of a previous example of this idea, please tell me.
Update: Fixed spelling of "psedo" (doh!) and link problem
Update 2: Was just browsing through the Camel. There is a similar structure used on pages 126 and 282-283 (third edition).
#!/usr/local/bin/perl
# A test to use a hash as a psuedo-switch statement
#
use strict;
use warnings;
my %PSUEDO_SWITCH = (
'1' => sub { print "One -- @_\n" },
'2' => sub { print "Two -- @_\n" },
'3' => sub { print "Three -- @_\n" },
'4' => sub { print "Four -- @_\n" },
);
my $match = 2;
&{ $PSUEDO_SWITCH{$match} }('arg1', 'arg2', 'arg3');
__OUTPUT__
Two -- arg1 arg2 arg3