Search code examples
perlscopeglobal-variablesstrict

Why do some variables require initialization and some don't in the same script?


I am experimenting with Perl, and have written the following quadratic equation solver.

#! perl
use strict;
use Math::Complex;
use v5.22;

say "Quadratic Equation Solver";

print "Enter a: ";
$a = <STDIN>;

print "Enter b: ";
$b = <STDIN>;

print "Enter c: ";
my $c = <STDIN>;

my $dis = ($b ** 2) - (4 * $a * $c);

say "x1 = ".((0 - $b + sqrt($dis)) / (2 * $a));
say "x2 = ".((0 - $b - sqrt($dis)) / (2 * $a));

If I leave out my when creating the variables $c and $dis, I get an error message that reads:

Global symbol "$c" requires explicit package name (did you forget to declare "my $c"?)
Global symbol "$dis" requires explicit package name (did you forget to declare "my $dis"?)

However, I do not get any error message for leaving it out by the variables $a and $b. Why is that? Furthermore, I am getting the error message even if I leave out use strict. I thought that Perl allows you to use uninitialized variables if you leave that out.


Solution

  • It's beacuse you happened to pick two variables ($a and $b) that are always declared as globals in all packages - so they can always be used without declaring them. If you'd chosen $A and $B instead, you'd get the same error as for $c and $dir if you leave my out.

    Further reading about $a and $b @ perlmaven.com: Don't use $a and $b outside of sort, not even for examples