gpt4 book ai didi

perl - perl 中访问散列变量的不同方式有哪些

转载 作者:行者123 更新时间:2023-12-05 00:19:32 25 4
gpt4 key购买 nike

根据我的基本理解,我们可以按如下方式访问哈希值:

$hash_name{key1}{key2};       #In case of an nested hash 
$hash_reference->{key1}{key2} #if we have the reference to the hash instead of the hash we can access as

但在其中一个存档代码中,我看到如下:
$sc1 = %par->{'a'}{'b'};
@a1 = %par->{'a'}{'c'};
%c3 = %par->{'a'}{'d'};

它实际上是什么意思?有人可以帮助我吗?

最佳答案

您发布的所有三个变体在 use strict 下都会产生语法错误,以及 use warnings 的附加警告在 Perl 5.22 之前的 Perls 上。我在这里展示的输出来自 Perl 5.20.1。

use strict;
use warnings;

my $par = { a => { b => 1, c => 2, d => 3 } };

my $sc1 = %par->{'a'}{'b'};
my @a1 = %par->{'a'}{'c'};
my %c3 = %par->{'a'}{'d'};

__END__
Using a hash as a reference is deprecated at /home/foo/code/scratch.pl line 700.
Using a hash as a reference is deprecated at /home/foo/code/scratch.pl line 701.
Using a hash as a reference is deprecated at /home/foo/code/scratch.pl line 702.
Global symbol "%par" requires explicit package name at /home/foo/code/scratch.pl line 700.
Global symbol "%par" requires explicit package name at /home/foo/code/scratch.pl line 701.
Global symbol "%par" requires explicit package name at /home/foo/code/scratch.pl line 702.
Execution of /home/foo/code/scratch.pl aborted due to compilation errors.

strictwarnings ,它会编译,但会产生废话。
no strict;
no warnings;
use Data::Printer;

my $par = { a => { b => 1, c => 2, d => 3 } };

my $sc1 = %par->{'a'}{'b'};
my @a1 = %par->{'a'}{'c'};
my %c3 = %par->{'a'}{'d'};

p $sc1;
p @a1;
p %c3;

__END__

undef
[
[0] undef
]
{
'' undef
}

也就是说,总是 use strictuse warnings对于您的 Perl 程序,并听取它向您显示的警告。

关于perl - perl 中访问散列变量的不同方式有哪些,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35651425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com