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

In reply to Case structures using a hash by hardburn

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.