Symptom: $c="foo"; throws an error and $b="foo"; does not.

My script is literally 3 lines. The following produces no errors or warnings
use strict;
$b = "foo";
print $b;
but if change to the following, I get a "requires explicit package name" error.
use strict;
$c = "foo";
print $c;,

I understand that use strict; requires variables to be declared before use, and changing $c = "foo"; to my $c = "foo"; does indeed prevent the error, but this alone does not explain the discrepancy.

Can anyone shed some light here? I'm sure I'm missing something obvious. I'm running Strawberry Perl v5.16.3 in Windows 7 x64. I'm editing in npp and executing my scripts from the command line, via c:\strawberry> perl test.pl

有帮助吗?

解决方案 2

Some global variables like $_, $a, $b are effectively predeclared. Therefore, the $a and $b variables can be used without extra declarations in a sort block, where they have the values of two items:

use strict;
my @nums = (1, 5, 3, 10, 7);
my @sorted = sort { $a <=> $b } @nums

其他提示

From the strict documentation:

Because of their special use by sort(), the variables $a and $b are exempted from this check.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top