http://www.perlmonks.org?node_id=301425


in reply to Re: Re: Re: Perl Idioms Explained: && and || "Short Circuit" operators
in thread Perl Idioms Explained - && and || "Short Circuit" operators

Im still confused how this works. :-) How does it map discontiguous values into a jump table without doing a lot of work?


---
demerphq

    First they ignore you, then they laugh at you, then they fight you, then you win.
    -- Gandhi


  • Comment on Re: Re: Re: Re: Perl Idioms Explained: && and || "Short Circuit" operators
  • Download Code

Replies are listed 'Best First'.
Re: Re: Re: Re: Re: Perl Idioms Explained: && and || "Short Circuit" operators
by fletcher_the_dog (Friar) on Oct 23, 2003 at 00:36 UTC
    Think of the c compiler doing something like this:
    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<@commands;$i++) { # execute code &{$commands[$i]} } } elsif (defined $mydefault) { &$mydefault; } } } my $switch = CompileSwitch( 'a'=>sub { print "a"}, 'b'=>sub { print "b"}, 'c'=>sub { print "c"; last}, 'x'=>sub { print "x"}, 'y'=>sub { print "y"}, 'z'=>sub { print "z"}, 'default'=>sub { print "unknown case"} ); foreach (qw(a b c d e f x y z)) { print "testing $_\n"; $switch->($_); 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