我引用的子程序很少,我需要将值传递给引用的子程序。 有没有办法做到这一点。
#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;
}
我想调用引用的子例程并将哈希的引用传递给它。
CreateSingleBox($hash_ref)
答案 0 :(得分:2)
您必须先访问哈希中的特定元素,然后才能将其作为coderef调用。即。
# WRONG! Variable $subCall does not exist.
my $htmlCode = $subCall->($box_html);
应该是
my $htmlCode = $subCall{box_type}($box_html);
结果代码如下所示:
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})