<?xml version="1.0" encoding="windows-1252"?>
<node id="301433" title="Re: Re: Re: Re: Re: Perl Idioms Explained: &amp;&amp; and || &quot;Short Circuit&quot; operators" created="2003-10-22 20:36:16" updated="2005-07-03 20:49:44">
<type id="11">
note</type>
<author id="214545">
fletcher_the_dog</author>
<data>
<field name="doctext">
Think of the c compiler doing something like this:
&lt;CODE&gt;
sub CompileSwitch{
  my %hash;
  my @commands;
  my $command = 0;
  my $mydefault;
  while (@_) {
    my $case = shift;
    my $code = shift;
    if ($case eq "default") {
      $mydefault = $code;
      last;
    }
    $hash{$case} = $command++;
    push @commands,$code;

  }
  return sub{
    my $case = shift;
    my $i = $hash{$case};
    if (defined $i) {
      # fall through , a C switch doesn't test following cases it
      # just goes to the end or till it hits a break
      for (;$i&lt;@commands;$i++) {
	# execute code
	&amp;{$commands[$i]}
      }
    }
    elsif (defined $mydefault) {
      &amp;$mydefault;
    }
  }
}

my $switch = CompileSwitch(
			   'a'=&gt;sub { print "a"},
			   'b'=&gt;sub { print "b"},
			   'c'=&gt;sub { print "c"; last},
			   'x'=&gt;sub { print "x"},
			   'y'=&gt;sub { print "y"},
			   'z'=&gt;sub { print "z"},
			   'default'=&gt;sub { print "unknown case"}
);

foreach (qw(a b c d e f x y z)) {
  print "testing $_\n";
  $switch-&gt;($_);
  print "\n";
}

__OUTPUT__
testing a
abc
testing b
bc
testing c
c
testing d
unknown case
testing e
unknown case
testing f
unknown case
testing x
xyz
testing y
yz
testing z
z

&lt;/CODE&gt;</field>
<field name="root_node">
301355</field>
<field name="parent_node">
301425</field>
</data>
</node>
