数组和哈希在perl中使用$符号声明

发布于 2025-02-11 17:25:19 字数 956 浏览 1 评论 0原文

当我遇到这个问题时,我正在研究Perl中的Arrow Operator:

# Perl program to demonstrate the Arrow Operator

#!/usr/local/bin/perl

use strict;
use warnings;

# reference to array
my $arr1 = [4,5,6];

# array inside array
my $arr2 = [4,5,[6,7]];

# reference to hash
my $has1 = {'a'=>1,'b'=>2};

# hash inside hash
my $has2 = {'a'=>1,'b'=>2,'c'=>[1,2],'d'=>{'x'=>3,'y'=>4}};

# using arrow operator
print "$arr1->[0]\n";
print "$arr2->[1]\n";
print "$arr2->[2][0]\n";
print "$has2->{'a'}\n";
print $has2->{'d'}->{'x'},"\n";
print $has2->{'c'}->[0],"\n";

在这里,使用$符号声明了阵列和哈希,但该代码对此运行良好。当我用 @和%符号替换声明中的$符号时,代码也产生了错误。此代码来自 geeksforgeekss

我浏览了互联网以进行解释,但在教育

I was studying arrow operator in perl when i came across this:

# Perl program to demonstrate the Arrow Operator

#!/usr/local/bin/perl

use strict;
use warnings;

# reference to array
my $arr1 = [4,5,6];

# array inside array
my $arr2 = [4,5,[6,7]];

# reference to hash
my $has1 = {'a'=>1,'b'=>2};

# hash inside hash
my $has2 = {'a'=>1,'b'=>2,'c'=>[1,2],'d'=>{'x'=>3,'y'=>4}};

# using arrow operator
print "$arr1->[0]\n";
print "$arr2->[1]\n";
print "$arr2->[2][0]\n";
print "$has2->{'a'}\n";
print $has2->{'d'}->{'x'},"\n";
print $has2->{'c'}->[0],"\n";

Here, arrays and hashes are declared using $ symbol, but the code runs perfectly fine with this. Also code incurred errors when i replaced the $ signs in the declaration with @ and % symbols. This code is from Geeksforgeeks.

I browsed the internet for explanation but found similar thing done on Educative.

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

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

发布评论

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

评论(1

秋意浓 2025-02-18 17:25:19

[]{}返回引用,引用是标量。

my $a = [ ... ];
my $h = { ... };

等同于

my @anon_a = ...;
my $a = \@anon_a;

my %anon_h = ...;
my $h = \%anon_h;

,这就是为什么您必须使用

$a->[0]    # Access an element of the array referenced by `$a`.

而不是

$a[0]      # Access an element of the array `@a`.

Both [] and {} returns a reference, and references are scalars.

my $a = [ ... ];
my $h = { ... };

is equivalent to

my @anon_a = ...;
my $a = \@anon_a;

my %anon_h = ...;
my $h = \%anon_h;

And that's why you have to use

$a->[0]    # Access an element of the array referenced by `$a`.

instead of

$a[0]      # Access an element of the array `@a`.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文