I have what I thought was a straightforward program.

#!/usr/bin/perl -w
use strict;

$a = 6;
$b = 9;
$c = 7;

print $a . "\n";
print $b . "\n";
print $c . "\n";

I assumed this would display:

6
9
7

and it does when I remove use strict; on line 2. When I leave it in the program, I get this error.

Global symbol "$c" requires explicit package name at C:\Users\Rick\Documents\PerlStuff\perlexperiment.pl line 6.
Global symbol "$c" requires explicit package name at C:\Users\Rick\Documents\PerlStuff\perlexperiment.pl line 10.
Execution of C:\Users\Rick\Documents\PerlStuff\perlexperiment.pl aborted due to compilation errors.

It gives me this error for c , but not a or b . a , b , and c are just variable names here, right?

The perl documentation would have explained all of your errors. But I'll short-cut it for you.

First, $a and $b are variables used by perl for sorting and should not be used by you except for that purpose. Since they are global package variables you don't have to declare them with "my".

Quoted from the sort functions documentation:

In the interests of efficiency the normal calling code for subroutines is bypassed, with the following effects: the subroutine may not be a recursive subroutine, and the two elements to be compared are passed into the subroutine not via @_ but as the package global variables $a and $b (see example below). They are passed by reference, so don't modify $a and $b . And don't try to declare them as lexicals either.

So $a and $b need to be changed and all your variable need to be declared within scope using "my".

#!/usr/bin/perl
use warnings; 
use strict;

my $x = 6;
my $y = 9;
my $c = 7;

print $x, "\n";
print $y, "\n";
print $c, "\n";

I changed "." to "," in the print lines because using the dot (concatenation) is slow. 'print' is a list operator so it expects a list of things to print, so using a comma to create a list of thing to print is very fast as it doesn't force perl to build any intermitent strings first.

Quoted from the print operators documentation:

Prints a string or a comma-separated list of strings.

Also note the use of "use warnings" in place of the -w switch. All modern versions of perl come with the warnings pragma and it should be used in place of the -w switch. You have more control over how it behaves and where it is used than the -w switch, which is an all or nothing proposition. See the warnings pragma documentation for more details.

commented: Helpful. +15
commented: Brilliant explanation to know something unknown :) +4

Awesome. That solved it. Thank you very much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.