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\n";
$sum % 2;
} 0..$#inp;
Here, the $sum
will be used in for loop, However in this case:
#!/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\n";
$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? What are the rules for autovivification?
This is not autovivification. You have a syntax mistake. If you had use strict
and use warnings
turned on, it would be more obvious.
The post-fix for
construct treats the left-hand side like a block. 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.
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.
You need to declare the variable first (and use strict
and warnings
!).