Alex Rivera | Logout

How to avoid errors with perl command line parameters and use strict

Asked 2012-03-07T03:34:56.037
8

Why is it that my code is not working after I added use strict; use warnings;? Is there a way to make it work?

Previously, the working code is:

#!/usr/bin/perl -s
print "x: $x\n";
print "y: $y\n";

The command that I ran is perl -s test.pl -x="hello" -y="world". The output is:

x: hello
y: world

However, after I added use strict; use warnings;, I got the following errors:

Variable "$x" is not imported at test.pl line 4.
Variable "$y" is not imported at test.pl line 5.
Global symbol "$x" requires explicit package name at test.pl line 4.
Global symbol "$y" requires explicit package name at test.pl line 5.
Execution of test.pl aborted due to compilation errors.

I know I need to declare my $x and my $y to fix the 3rd and 4th error. But what does the first 2 errors mean and how do I overcome it?

Edit
Report

1 Answer

9

Actually, declaring these variables as lexical (my) variables will not help, because it's too "late": the -s switch will already have set them. It sets the global (package) variables (in your case, $main::x and $main::y, or — as a special shorthand — $::x and $::y). If you don't want to have to refer to them using their package-qualified names, then you can use an our declaration to indicate that the bare names $x and $y refer to the $x and $y in the current package:

our ($x, $y);
print "x: $x\n"; 
print "y: $y\n";

(Hat-tip to derobert for pointing out that you can use our for this.)

Alternatively, you can copy the global variables into identically-named lexical variables:

my ($x, $y) = ($::x, $::y);
print "x: $x\n";
print "y: $y\n";

This will take care of both sets of diagnostics.

answered 2012-03-07T03:55:03.420

Your Answer