4

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.

qwerty
  • 810
  • 1
  • 9
  • 26

1 Answers1

5

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

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • Thank you, however, why am I getting the warnings even when I leave out `use strict`? – qwerty Apr 18 '21 at 18:53
  • 1
    @ap You're welcome. What warnings? I don't see anything about warnings in your question – Ted Lyngmo Apr 18 '21 at 18:54
  • I am getting the same error messages even if I leave out `use strict`, but I'm not sure why. – qwerty Apr 18 '21 at 18:55
  • 5
    @ap It's because you `use v5.22;` - "_if the specified Perl version is greater than or equal to 5.12.0, strictures are enabled lexically as with `use strict`._" – Ted Lyngmo Apr 18 '21 at 19:04