calling subroutine via hash

J

John W. Burns

The following code calls only the first subroutine not the second. It seems
to
recoginize 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 when run as standard routines and not part of
a hash work.Thanks
JWB

#!/usr/local/bin/perl
use warnings;
# following example reflects Perl Cookbook 11.4
my $name;
my $key;
my $dispatch;
my $var;

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"){ #note:pCB uses chomp($input = <STDIN>) in
lieu of "foreach"
if ( exists ${dispatch}{ $input } ) {
${dispatch} {$input}( );
print "$input is the answer.\n";
}
else {
die "Cannot find the subroutine $input\n";
}

}
 
M

MikeGee

my $radius_ref = @data;

This does not create an arrayref. You want:
my $radius_ref = \@data;
 
M

Matt Garrish

John W. Burns said:
The following code calls only the first subroutine not the second. It
seems
to
recoginize 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 when run as standard routines and not part of
a hash work.Thanks

They both run...
#!/usr/local/bin/perl
use warnings;
# following example reflects Perl Cookbook 11.4
my $name;
my $key;
my $dispatch;
my $var;

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;

Your problem is here, however. You're assigning the count of @data to the
scalar...
foreach $radius(@$radius_ref) {

And then trying to call it as an array ref, which it is not Change that
assignment to:

my $radius_ref = \@data;

Or just get rid of this useless assignment altogether and write:

foreach my $radius (@data) {

Matt
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top