Symptom: $c="foo";
throws an error and $b="foo";
does not.
My script is literally 3 lines. The following produces no errors or warningsuse 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
$@ The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.
The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − #!/usr/bin/perl foreach ('hickory','dickory','doc') { print $_; print "\n"; }
Perl variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
Hence, three types of variables will be used in Perl. A scalar variable can store either a number, a string, or a reference and will precede by a dollar sign ($). An array variable will store ordered lists of scalars and precede by @ sign.
From the strict documentation:
Because of their special use by sort(), the variables $a and $b are exempted from this check.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With