Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Case structures using a hash

by hardburn (Abbot)
on Dec 13, 2002 at 18:57 UTC ( [id://219697]=CUFP: print w/replies, xml ) Need Help??

Many languages support a switch/case structure for only evaluating a condition once. Perl has no such official structure, though there are several ways of getting the same idea without it. However, these ways are not as efficent as the "real" switch/case structures you get in C or Java. Larry has said that an offical structure will be added in Perl6, but that doesn't help us right now.

I was inspired by a post by pg, where he made a point about a "switch" structure in the parent node, and another unrelated point about using a hash instead of an array. For some reason, these two seemingly seperate points made by brain click some peices together. Why not use a hash as a switch/case structure, using subroutine referances to execute the actual case? This should give us all the benifits of the single-evaluation of the equivilent C structure. We can even pass arguments into the case.

I've searched around a bit and haven't seen this used before. If anyone knows of a previous example of this idea, please tell me.

Update: Fixed spelling of "psedo" (doh!) and link problem

Update 2: Was just browsing through the Camel. There is a similar structure used on pages 126 and 282-283 (third edition).

#!/usr/local/bin/perl # A test to use a hash as a psuedo-switch statement # use strict; use warnings; my %PSUEDO_SWITCH = ( '1' => sub { print "One -- @_\n" }, '2' => sub { print "Two -- @_\n" }, '3' => sub { print "Three -- @_\n" }, '4' => sub { print "Four -- @_\n" }, ); my $match = 2; &{ $PSUEDO_SWITCH{$match} }('arg1', 'arg2', 'arg3'); __OUTPUT__ Two -- arg1 arg2 arg3

Replies are listed 'Best First'.
(jeffa) Re: Case structures using a hash
by jeffa (Bishop) on Dec 13, 2002 at 22:30 UTC
Re: Case structures using a hash
by BronzeWing (Monk) on Dec 13, 2002 at 19:23 UTC

    ++!
    But what about an else/default case? I'd put something like this:

    &{ ($PSUEDO_SWITCH{$match}||$PSUEDO_SWITCH{'ELSE'}) }('arg1', 'arg2', 'arg3');

    -BronzeWing


    Perl Monks do it more than one way.

      Excelent point. If you need a "default" case, that is probably the best way to do it.

      Also, I'm wondering about ways of performing fall-through on the cases. Perhaps the end of each subroutine could call explicitly call the next referance?

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (1)
As of 2024-04-25 01:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found