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?
You are using a a rudimentary switch parser
perl -s, which uses global variables. To make it work withuse strictyou need to refer to the globals:$main::xas ruakh pointed out.But even so, lexical variables (declared with
my) are preferable in just about all cases. Just do:And use with:
For a more detailed and switch like handling, check out the Getopt::Long module.