Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

perl - 自活甚至不能作为左值(Autovivification doesnt work even as lvalue)

I have this simple code:

(我有这个简单的代码:)

 #!/usr/bin/perl
@inp = map 2**$_, 0..6;
@cc = grep {
    my $num = $inp[$_];
    my $sum;    #---- HERE, I have to have the var declared first, before init.
    $sum += $_ for (split //, $num);
    print "$sum
";
    $sum % 2;
    } 0..$#inp;

Here, the the $sum will be used in for loop, However in this case:

(在这里, $sum将用于for循环,但是在这种情况下:)

#!/usr/bin/perl
@inp = map 2**$_, 0..6;
@cc = grep {
    my $num = $inp[$_];
    my $sum += $_ for (split //, $num); # HERE, Trying to autovificate - wont work
    print "$sum
";
    $sum % 2;
    } 0..$#inp;

But when I used var $sum at the same line with for loop - that means I am trying to declare and initiate at once - where should work the autovivifaction - As i would expect to autovivificate the $sum to zero (because used with math operator += ), but will not work, but why so?

(但是,当我在for循环的同一行上使用var $sum时-这意味着我试图立即声明和初始化-autovivifaction应该在哪里工作-正如我希望将$sum实现为零(因为与数学运算符一起使用+= ),但不起作用,但为什么会这样呢?)

What are the rules for autovivification?

(自我生存的规则是什么?)

  ask by Herdsman translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is not autovivification.

(这不是自发生存。)

You have a syntax mistake.

(您有语法错误。)

If you had use strict and use warnings turned on, it would be more obvious.

(如果您use strictuse warnings ,那将更加明显。)

The post-fix for construct treats the left-hand side like a block.

(该修复后for构建体的治疗左侧像块。)

So there is a scope for the body of the loop.

(因此,循环的主体存在范围。)

Therefore you are declaring your my $sum inside that loop body scope, and it's not visible outside.

(因此,您在该循环主体范围内声明了my $sum ,并且在外部它不可见。)

If you turn on use warnings , you'll get Use of uninitialized value $sum in concatenation (.) or string at ... line 6 , which is the print after.

(如果打开use warnings ,则会在...第6行的连接(。)或字符串中获得未初始化值$ sum的使用 ,此后是print 。)

You need to declare the variable first (and use strict and warnings !).

(您需要先声明变量(并使用strictwarnings !)。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...