Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在perl中将值传递给引用的子例程_Perl_Subroutine - Fatal编程技术网

在perl中将值传递给引用的子例程

在perl中将值传递给引用的子例程,perl,subroutine,Perl,Subroutine,我有几个被引用的子例程,我需要将值传递给被引用的子例程。 有办法吗 #Sample Code sub CreateHtmlBox { my ($box_type,$hash_ref) = @_; my %subCall = ( 'singlebox' => \&CreateSingleBox , 'multiplebox' => \&CreateMultipleBox

我有几个被引用的子例程,我需要将值传递给被引用的子例程。 有办法吗

   #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)

您必须先访问散列中的特定元素,然后才能将其作为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})
使用严格;
使用警告;
子CreateHtmlBox{
我的($box\u type,$hash\u ref)=@;
我的%subCall=(
singlebox=>\&CreateSingleBox,
multiplebox=>\&创建multiplebox,
);
返回$subCall{$box\u type}($hash\u ref);
}
子框{
我的($box\u type)=@;
我的$htmlCode=“”$box_type->{a}。”

”; 返回$htmlCode; } 打印CreateHtmlBox(“singlebox”,{a=>1})
不清楚需要传递给正在调用的子例程的值。无论如何,您的示例中缺少一个级别:
$subCall->($box\u html)
应该是(假设您要调用
CreateSingleBox
):
$subCall{singlebox}->($box\u html)