Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Re: Re: Perl Idioms Explained: && and || "Short Circuit" operators

by fletcher_the_dog (Friar)
on Oct 22, 2003 at 23:17 UTC ( [id://301421]=note: print w/replies, xml ) Need Help??


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

C switch statements create an internal jump table that is more or less like a hash so that they can skip testing cases that are are going to fail, this makes them O(1). For example in the following switch statement if 'test' equals 'c' the code jumps right to case 'c', it doesn't test to see if 'test' equals 'a' or 'b':
switch(test){ case 'a': # do something case 'b': # do something else case 'c': # do something else }
This of course means that the possible cases (but not the test value) are static and must be known at compile time which decreases flexibilty but increases speed.

Replies are listed 'Best First'.
Re: Re: Re: Re: Perl Idioms Explained: && and || "Short Circuit" operators
by demerphq (Chancellor) on Oct 22, 2003 at 23:35 UTC

    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


      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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://301421]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (2)
As of 2024-03-19 06:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found