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
CB 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";
}
}
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
lieu of "foreach"
if ( exists ${dispatch}{ $input } ) {
${dispatch} {$input}( );
print "$input is the answer.\n";
}
else {
die "Cannot find the subroutine $input\n";
}
}