在perl中的子例程中访问全局哈希

iDe*_*Dev 1 perl hash global-variables subroutine

我创建了一个全局哈希,当我尝试从perl子例程中访问该哈希时,它无法访问它.

我已将其声明为: %HASH = ();

并尝试在子例程中访问它:

$HASH{$key} = $value;
Run Code Online (Sandbox Code Playgroud)

如果我做错了,请指导我

mem*_*owe 8

这里工作正常:

#!/usr/bin/env perl

use strict;
use warnings;
use feature 'say';

our %truth = (); # "global" truth: lexical name
                 # for the package variable %main::truth

sub add_to_truth {
    my ($thing, $value) = @_;
    $truth{$thing} = $value;
}

add_to_truth(answer => 42);
say $truth{answer};
Run Code Online (Sandbox Code Playgroud)

输出:

42
Run Code Online (Sandbox Code Playgroud)

请注意,在严格的 ures下,您必须使用其包名称(%main::truth在本例中)完全限定"全局"变量,或者使用我们的名称为它们创建一个词法范围的本地名称.今天编程没有限制(和警告)并不是一件好事.事实上,激活它们会告诉你一些有用的东西.