Search code examples
perlvariablesstrict

Variable behavior, name-based discrepancy


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 I 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


Solution

  • 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