7

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

4

2 回答 2

17

严格的文档中:

由于 sort() 对它们的特殊使用,变量 $a 和 $b 不受此检查。

于 2013-07-15T21:01:15.523 回答
8

一些全局变量,如$_, $a,$b是有效地预先声明的。因此,$aand$b变量可以在没有额外声明的情况下在sort块中使用,其中它们具有两项的值:

use strict;
my @nums = (1, 5, 3, 10, 7);
my @sorted = sort { $a <=> $b } @nums
于 2013-07-15T21:02:19.347 回答