package myswitch; require Exporter; @ISA = qw(Exporter); @EXPORT = qw(switch); use carp; sub switch ($%) { my ( $expr, $cases ) = @_; my $default = $cases->{default} and delete $cases->{default} if exists $cases->{default}; my $selector = eval $expr; carp $@ if $@; for (keys %{$cases} ) { $cases->{$_}() and return if eval $_ eq $selector; } $default->(); } 1; =pod Name: (Currently) MySwitch.pm Purpose: To provide a simulated switch statement for Perl. Features: Arbitrary selector and case expression. It uses nothing but standard Perl so conflicts with other modules should be minimal. Caveats: Testing so far is minimal. It captures the symantics of the switch statement, but the syntax is slightly odd --but maybe as its Perl that doesn't matter too much. If only prototypes were more consistant, specifically if (&) did the same thing when it was the second element of the prototype as it does when the first a much nicer syntax could be achieved. There is no fall-thru of cases as with the C equivalent (not a bad thing in my book!) I make no claims for efficiency as the cases are evaluated in hash order. If multiple case expressions evaluate to the same value and match the selector expression the case executed is the first discovered in hash key order (Ie. basically random) but it should be consistant. Author: BrowserUk c/o PerlMonks.com Copyright 2002, BrowserUk at PerlMonks.com Its free and without warrenty of any kind. Use it as you will at your own risk. =cut