Perl, variable behavior, name mismatch

Symptom: $c="foo"; gives an error, and $b="foo"; - not.

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

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

Can anyone shed some light? I am sure that I am missing something obvious. I am running Strawberry Perl v5.16.3 on Windows 7 x64. I edit npp and execute my scripts from the command line using c:\strawberry> perl test.pl

+7
variables perl strict
source share
2 answers

Some global variables, such as $_ , $a , $b , are effectively predefined. Therefore, the variables $a and $b can be used without additional declarations in the sort block, where they have the values โ€‹โ€‹of two elements:

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

In the strict documentation:

Due to their special use of sort (), the variables $ a and $ b are exempt from this check.

+17
source share

All Articles