Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl, 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 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

like image 518
mic angelo Avatar asked Jul 15 '13 20:07

mic angelo


People also ask

What is $@ in Perl?

$@ 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.

What is the meaning of $_ in Perl?

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"; }

How do I declare a variable in Perl?

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.

How many types of built in variables are in Perl?

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.


2 Answers

From the strict documentation:

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

like image 150
toolic Avatar answered Oct 22 '22 08:10

toolic


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
like image 37
amon Avatar answered Oct 22 '22 08:10

amon