Home > Archive > PERL Beginners > January 2006 > calling subroutine via hash
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
calling subroutine via hash
|
|
| John W. Burns 2006-01-10, 4:02 am |
| 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";
}
}
| |
| Tom Phoenix 2006-01-10, 4:02 am |
| On 1/3/06, John W. Burns <vzeo882n@verizon.net> wrote:
> my $radius_ref =3D @data;
Could you have omitted a backslash on that line? Your code does what I
think it should do, when I add the backslash before the @-sign. Hope
this helps!
--Tom Phoenix
Stonehenge Perl Training
| |
| Gautam Dey 2006-01-10, 4:02 am |
| John,
The problem is not that it does not call the second subroutine,
but that the
second subroutine does not output anything.
On Jan 3, 2006, at 12:39 PM, John W. Burns wrote:
[cut]
>
> 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 error is the the above line. That line should be:
my $radius_ref = \@data;
Since you want the reference to the data array.
[cut]
Hope that helps.
Gautam Dey.
|
|
|
|
|