我试图理解在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 { ... }
,所以你在之后放的是意外的并导致语法错误.