PERL:使用来自匿名哈希的数据

发布于 2025-02-13 20:52:28 字数 213 浏览 1 评论 0原文

我正在添加到其他开发人员代码中,我们都是Perl的新手,我正在尝试列出IPS并通过WHOIS运行它。我不确定如何访问匿名哈希中的数据,如何使用它? 他告诉我数据存储在其中。这是我唯一可以提及哈希的实例:

## Instantiate a reference to an anonymous hash (key value pair)
my $addr = {};

I am adding on to another developers code, we are both new to perl I am trying to take a list of IPs and run it through whois. I am unsure how to access the data in the anonymous hash, how do I use it?
He told me the data was stored inside one. This is the only instance I could find mentioning a hash:

## Instantiate a reference to an anonymous hash (key value pair)
my $addr = {};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏末 2025-02-20 20:52:28

匿名哈希是{} part。它返回一个可以存储在标量变量中的引用,例如在您的示例中:

my $addr = {};

要查看结构,您可以使用 data :: Dumper

use Data::Dumper;
print Dumper $addr;

内容:

$VAR1 = {
          'c' => 1,
          'a' => 2
        };

您使用箭头操作员访问哈希键:

print $addr->{"a"}

它可能向您显示类似的 您将如何访问常规哈希,但是介于两者之间的箭头操作员。

您可以通过将sigil放在前面放置参考

%$addr

# compare %addr  %$addr
#          hash   hashref dereferenced

The anonymous hash is the {} part. It returns a reference which can be stored in a scalar variable, like in your example:

my $addr = {};

To see the structure, you can print it with Data::Dumper:

use Data::Dumper;
print Dumper $addr;

It might show you something like:

$VAR1 = {
          'c' => 1,
          'a' => 2
        };

You access the hash keys using the arrow operator:

print $addr->{"a"}

Like how you would access a regular hash, but with the arrow operator in between.

You can dereference the reference by putting a hash sigil in front

%$addr

# compare %addr  %$addr
#          hash   hashref dereferenced
悍妇囚夫 2025-02-20 20:52:28

这是一个匿名哈希:

my $anon_hash = {
  key1 => 'Value 1',
  key2 => 'Value 2',
  key3 => 'Value 3',
}

如果要访问单个值:

my $value = $anon_hash->{key1};
say $anon_hash->{key2};

如果要更新单个值:

$anon_hash->{key3} = 'New value 3';

如果要添加新的键/值对:

$anon_hash->{key4} = 'Value 4';

也可以使用所有标准哈希功能(例如 keys() )。您只需要“尊重”您的哈希参考 - 这意味着将'%'放在面前。

因此,例如,打印所有密钥/值对:

foreach my $key (keys %$anon_hash) {
  say "$key : $anon_hash->{$_}";
}

Here is an anonymous hash:

my $anon_hash = {
  key1 => 'Value 1',
  key2 => 'Value 2',
  key3 => 'Value 3',
}

If you want to access an individual value:

my $value = $anon_hash->{key1};
say $anon_hash->{key2};

If you want to update an individual value:

$anon_hash->{key3} = 'New value 3';

If you want to add a new key/value pair:

$anon_hash->{key4} = 'Value 4';

You can also use all of the standard hash functions (e.g. keys()). You just need to "deference" your hash reference - which means putting a '%' in front of it.

So, for example, to print all the key/value pairs:

foreach my $key (keys %$anon_hash) {
  say "$key : $anon_hash->{$_}";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文