Dear Monks:

I have been trying various ways to call multiple subroutines(windows XP, OS) (I'm writing a Tk program that has serveral hundred Tk callbacks) and so far have been unsuccessful. I'm a beginner and my Perl knowledge is limited, and more mechanical than intuitive.

The following experimental code calls only the first subroutine not the second.
It seems to recognize both subroutines but executes only the first one.

Can anyone help me figure out how to get the code to call the second subroutine as well?

Both subroutines work when run as standard named routines and not part of a hash.


Thanks

JWB
#!/usr/local/bin/perl use warnings; my $key; my $dispatch; my %dispatch = ( "foo" => sub { my $x = 3; my $ans = ($x**2); print "answer is: $ans \n"; #prints "answer is: 9" }, "moo" => sub { my @data = (3,7,15,28); my $radius; my $radius_ref = @data; foreach $radius(@$radius_ref) { print "my radius is: $radius \n"; my $area = 3.14159 * ( $radius ** 2); print "and circle area is $area \n"; } } ); #Perl PCB 5.2 reference my $input; foreach $input("foo", "moo"){ if ( exists ${dispatch}{ $input } ) { ${dispatch} {$input}( ); print "$input is the answer.\n"; } else { die "Cannot find the subroutine $input\n"; } }
#when code is run, "the answer is 9" is printed along with "moo is the answer" and "foo is the answer".

In reply to call subroutines via hash by fortesque

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.