Reputation: 2279
I have few referenced subroutine and I need to pass the value to the referenced subroutine. Is there any way to do it.
#Sample Code
sub CreateHtmlBox {
my ($box_type,$hash_ref) = @_;
my %subCall = (
'singlebox' => \&CreateSingleBox ,
'multiplebox' => \&CreateMultipleBox
);
my $htmlCode = $subCall->($box_html);
}
sub CreateSingleBox {
my ($box_type) =@_;
#...................
return $htmlCode;
}
I want to call referenced subroutine and pass the reference of hash to it.
CreateSingleBox($hash_ref)
Upvotes: 0
Views: 67
Reputation: 34327
You have to access an specific element in the hash before you can call it as a coderef. I.e.
# WRONG! Variable $subCall does not exist.
my $htmlCode = $subCall->($box_html);
should really be
my $htmlCode = $subCall{box_type}($box_html);
The resulting code would look like this:
use strict;
use warnings;
sub CreateHtmlBox {
my ($box_type, $hash_ref) = @_;
my %subCall = (
singlebox => \&CreateSingleBox,
multiplebox => \&CreateMultipleBox,
);
return $subCall{$box_type}($hash_ref);
}
sub CreateSingleBox {
my ($box_type) = @_;
my $htmlCode= "<p>" . $box_type->{a} . "</p>";
return $htmlCode;
}
print CreateHtmlBox("singlebox",{a => 1})
Upvotes: 2