【问题标题】:Why do some variables require initialization and some don't in the same script?为什么有些变量需要初始化而有些变量不需要在同一个脚本中?
【发布时间】:2021-07-13 01:34:32
【问题描述】:

我正在尝试使用 Perl,并编写了以下二次方程求解器。

#! 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));

如果我在创建变量 $c$dis 时遗漏了 my,则会收到一条错误消息:

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"?)

但是,变量$a$b 忽略了它,我没有收到任何错误消息。这是为什么?此外,即使我遗漏了use strict,我也会收到错误消息。我认为 Perl 允许您使用未初始化的变量,如果您忽略它的话。

【问题讨论】:

    标签: perl scope global-variables strict


    【解决方案1】:

    这是因为您碰巧选择了两个变量($a$b),它们在所有包中始终声明为全局变量 - 因此它们始终可以在不声明的情况下使用。如果您选择了 $A$B,如果您将 my 排除在外,则会收到与 $c$dir 相同的错误。

    进一步阅读 $a$b @ perlmaven.com: Don't use $a and $b outside of sort, not even for examples

    【讨论】:

    • 谢谢,但是为什么即使我忽略了use strict,我也会收到警告?
    • @ap 不客气。什么警告?我在您的问题中没有看到任何有关警告的信息
    • 即使我忽略了use strict,我也会收到相同的错误消息,但我不知道为什么。
    • @ap 是因为你use v5.22; - "如果指定的 Perl 版本大于或等于 5.12.0,则像 use strict 一样在词法上启用限制。 "
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 2015-09-09
    • 2018-06-11
    • 1970-01-01
    相关资源
    最近更新 更多