[英]Perl hash, array and references
I have this 3 lines of code in a sub and I'm trying to write them together on one line only.. but I'm quite lost 我在子代码中有这三行代码,而我试图只在一行中一起编写它们。.但是我很迷茫
my %p = @_;
my $arr = $p{name};
my @a = @$arr;
what's the correct way of doing this? 正确的做法是什么?
thank you! 谢谢!
my %p = @_;
@_
is assumed to contain key-value pairs which are then used to construct the hash %p
. 假定
@_
包含键值对,然后将其用于构造哈希%p
。
my $arr = $p{name};
The argument list is assumed to have contained something along the lines of name, [1, 2, 3,]
so that $p{name}
is an reference to an array. 假定参数列表包含沿
name, [1, 2, 3,]
因此$p{name}
是对数组的引用。
my @a = @$arr;
Dereference that array reference to get the array @
. 解引用该数组引用以获取数组
@
。
Here is an invocation that might work with this prelude in a sub
: 这是一个可以在
sub
与此前奏配合使用的调用:
func(this => 'that', name => [1, 2, 3]);
If you want to reduce the whole prelude to a single statement, you can use: 如果要将整个前奏简化为单个语句,可以使用:
my @a = @{ { @_ }->{name} };
as in: 如:
#!/usr/bin/env perl
use strict;
use warnings;
use YAML::XS;
func(this => 'that', name => [1, 2, 3]);
sub func {
my @a = @{ { @_ }->{name} };
print Dump \@a;
}
Output: 输出:
--- - 1 - 2 - 3
If the array pointed to by name
is large, and if you do not need a shallow copy, however, it may be better to just stick with references: 如果阵列指向
name
是大的,如果你并不需要一个浅拷贝,但是,它可能是更好的只是引用坚持:
my $aref = { @_ }->{ name };
OK so what you're doing is: 好的,所以您正在做的是:
Now, I'm going to have to make some guesses as to what you're putting in : 现在,我将不得不做出一些猜测到你把什么 :
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
sub test {
my %p = @_;
my $arr = $p{name};
my @a = @$arr;
print Dumper \@a;
}
my %input = ( fish => [ "value", "another value" ],
name => [ "more", "less" ], );
test ( %input );
So with that in mind: 因此请牢记:
sub test {
print join "\n", @{{@_}->{name}},"\n";
}
But actually, I'd suggest what you probably want to do is pass in the hashref in the first place: 但实际上,我建议您可能首先要做的是将hashref传递给:
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
sub test {
my ( $input_hashref ) = @_;
print Dumper \@{$input_hashref -> {name}};
}
my %input = ( fish => [ "value", "another value" ],
name => [ "more", "less" ], );
test ( \%input );
Also: 也:
a
and b
because $a
and $b
are for sorting. a
和b
来说是两倍,因为$a
和$b
用于排序。 (And using @a
is confusing as a result). @a
会造成混淆)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.