[Pdx-pm] OT given/when in Perl5

Austin Schutz tex at off.org
Sat May 20 03:09:37 PDT 2006


On Fri, May 19, 2006 at 09:57:09PM -0700, Eric Wilhelm wrote:
> Hi all,
> 
> I got to thinking about how a switch syntax might be done in Perl5 with 
> a little prototype-based syntactic sugar.
> 
>   http://scratchcomputing.com/tmp/given_when.pl
> 
> (This is just a first hack to work out the semantics.)

	This has come up in the past on this list.

	I've been known to do something like:

while(defined($_ = shift(@ARGV))){
  /^-file/ && do {
    $filename = shift(@ARGV);
  };
  /^-debug/ && do {
   ...
  };
  ...
}

	With a little extra work you can set defaults and have it not fall
from case to case after a correct match. That's left as an exercise to the
reader (who probably doesn't do this sort of thing anyway).

	You can also do something akin to a jump table, like:

%subs_by_test = (
   'foo' => sub { 1; },
   'bar' => sub { 2; },
   ...
);

if (exists($subs_by_test{$test})) {
  &{ $subs_by_test{$test} };
  # Alternatively you could keep the same @_
} else {
  # default.
}

	That's probably a bit less code where there are many cases.

	Ymmv.

	Austin


More information about the Pdx-pm-list mailing list