There is also another possibility besides "given", use a hash table. A simple translation like this could fit your needs:
my %ops=(add=>4, sub=>5); Instead of writing "given" code, just do a hash look up. Often replacing code with a static data table lookup is a good idea.

It is also possible to have a hash table which contains code references to subroutines. This is called a dispatch table. I just show a simple example below. There are all sorts of permutations that can be done using this theme. Setting something like this up can be relatively hard or low performance in other languages but, not so in Perl.

Have fun!

#!/usr/bin/perl use warnings; use diagnostics; use strict; my %opcodes = ('add'=> sub{ print "the add opcode was passed operands: @_\n"; print "The opcode reported was add with hex value 4\ +n";}, 'sub'=> \&opcode_sub, ); while (my $instruction = <DATA>) { my ($opcode, @operands) = split (/\s+/, $instruction); print "\ninstruction: $opcode operands: @operands\n"; print "calling $opcode...\n"; $opcodes{$opcode}->(@operands); # give some data to subroutine #$opcodes{$opcode}->(); # or no args } sub opcode_sub { print "The code for subtract opcode was passed these operands: @_\n +"; print "The opcode reported was add with hex value 5\n"; } =outputs instruction: add operands: 5 6 10 calling add... the add opcode was passed operands: 5 6 10 The opcode reported was add with hex value 4 instruction: sub operands: 7 8 calling sub... The code for subtract opcode was passed these operands: 7 8 The opcode reported was add with hex value 5 =cut __DATA__ add 5 6 10 sub 7 8

In reply to Re: Switch statement giving out error by Marshall
in thread Switch statement giving out error by wisemonkey

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.