0

我引用的子例程很少,我需要将值传递给引用的子例程。有没有办法做到这一点。

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

1 回答 1

2

您必须先访问哈希中的特定元素,然后才能将其称为 coderef。IE

# 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})
于 2013-04-09T12:35:17.707 回答