I am trying to use the following conventions I have been instructed to use for good/proper/safe Perl code for my "Hello, World!"
Program:
use strict;
use warnings;
I have created and successfully run the following "Hello World" program using (Strawberry) Perl 5.12 on my main Windows 7 OS:
!#/usr/bin/perl
use strict;
use warnings;
print "Hello, World!\n";
What I got back, as expected, was "Hello, World!"
.
What struck me as very odd was that the same program run in terminal on my virtualized Linux Mint 14 OS, using Perl 5.14, produced the following error:
"use" not allowed in expression at /PATH/hello_world.pl line 2, at end of line
syntax error at /PATH/hello_world.pl line 2, near "use strict"
BEGIN not safe after errors--compilation aborted at /PATH/hello_world.pl line 3.
I created other "Hello World" programs subsequently without either the use strict;
or use warnings;
lines, and also one with the -w
, which I had seen in some tutorials, indicating, if I am not mistaken, that warnings would be turned on.
Both of my alternate versions worked properly in that they produced my expected result:
Hello, World!
What I cannot be sure of is if I need the use
statements in Perl programs from version 5.14 and up or if it is just fine to write the -w
at the end of my first line.
I would like to think that I could use a consistent header, so to speak, in all of my Perl programs, whether they are Windows or Linux, Perl 5.12 or 5.14 or otherwise.
Your image shows that all of your scripts start with !#/usr/bin/perl
. This is wrong. It is not a valid she-bang line, it is read as negation !
followed by a comment #
. The parsing will continue and with script1.pl perl will execute ! print "Hello world.\n";
. This will print Hello world
and negate the result of print
... not really useful, but valid perl.
In script2.pl perl sees ! use strict;
and this is a compile time error and therefor perl fails and reports the error for the line use strict;
.
So if you use correct she-bang lines, all three scripts will work as designed.
Edit (test scripts added):
script1.pl
!#/usr/bin/perl
print "Hello world.\n" ;
Calling perl script1.pl
gives
Hello world.
script2.pl
!#/usr/bin/perl
use strict;
use warnings ;
print "Hello world.\n" ;
Calling perl script2.pl
gives
"use" not allowed in expression at script2.pl line 3, at end of line
syntax error at script2.pl line 3, near "use strict "
BEGIN not safe after errors--compilation aborted at script2.pl line 4.
Using the correct syntax script3.pl
#!/usr/bin/perl
use strict ;
use warnings ;
print "Hello world.\n" ;
Calling perl script3.pl
gives
Hello world.