为什么我不能将此perl子分配给一个变量?

我试图理解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似乎没有问题。

我想将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()的参数。 当我将sub分配给变量时,它没有抱怨。

即使我明确地将子程序引用为$ &sub,它也会执行相同的操作。

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


您在语句$imapSub = sub { ... }括号后面缺少分号,因此无论您在此之后放置的是何种意外,都会导致语法错误。

链接地址: http://www.djcxy.com/p/59225.html

上一篇: Why can't I assign this perl sub to a variable?

下一篇: the best way to replace regular alarm