Not sure if this is worthy of production code use yet as I'm still playing with it. It might never be. I offer it for consideration anyway.
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 t
+he same thing when
it was the second element of the prototype as it does when the fir
+st 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. b
+asically 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
Short, far-from-comprehensive test program.
#! perl -sw
use strict;
use MySwitch;
switch 4/2 => { # Abitrary expression for s
+elector.
1 => sub {
print 'Expression equals 1'.$/;
}, # NOTE: comma not semicolon
+.
length 'xx' => sub { # Arbitrary expression for eac
+h case.
print 'Expression equals 2'.$/;
},
3 => sub {
print 'Expression equals 3'.$/;
},
default => sub { # default case (if supplied) u
+sed if no match.
print 'Expression failed to match any given case'.$/;
},
};
__END__
# Output
C:\test>switchtest
Expression equals 2
C:\test>
Cor! Like yer ring! ... HALO dammit! ... 'Ave it yer way! Hal-lo, Mister la-de-da. ... Like yer ring! |