为什么我不能将这个perl sub分配给变量?

时间:2015-12-31 00:58:23

标签: perl reference subroutine

我试图理解HOP第158页上的imap例程的复杂执行路径。

此代码有效

# code from rng-iterator.pl
sub make_rand {
my $seed = shift || (time & 0x7fff);
print "\nin make_rand, at6: seed=$seed";
return sub 
    {   $seed = (29*$seed+11111) & 0x7fff;
print "\nin make_rand sub, at9: seed=$seed";
        return $seed; 
    }
}

# code adapted from HOP p.158, to make an iterator version of map
sub imap {
    my ($transform, $it) = @_;
print "\nin imap, at17";
    return sub 
    {   my $next = $it->();
print "\nin imap sub, at20, next=$next";
        return unless defined $next;
        $newVal = $transform->($next);
print "\nin imap sub, at23, newVal=$newVal";
        return $newVal;
    }
}

# to return random number 0 .. 1
$rng = imap(sub {$_[0] / 37268}, make_rand(1)); # set seed 
print "\nin main at30, rng=$rng";
while (<>) {    
    my $random = $rng->();  
    print "\nin main, at 32: random=$random";
}

将子(imap)的引用返回到字符串$ rng似乎没有问题,并使用它来指向imap的子。

我想将sub分配给imap的字符串INSIDE,并返回字符串,如下所示:

    $imapSub =  sub 
        {   my $next = $it->();
                print "\nin imap sub, at20, next=$next";
            return unless defined $next;
            $newVal = $transform->($next);
                print "\nin imap sub, at23, newVal=$newVal";
            return $newVal;
        }
    return $imapSub;

当我尝试返回或打印$ imapSub时,Perl报告了语法错误,甚至将其用作ref()的参数。当我将子分配给变量时,它并没有抱怨。

即使我明确地将子例程的引用转换为$ \&amp; sub也是如此。

当我尝试使用引用时,为什么会出现语法错误?

1 个答案:

答案 0 :(得分:6)

在语句$imapSub = sub { ... }中的右括号后面缺少分号,所以在此之后放置的是意外的并导致语法错误。