Léo*_* 준영 2 arrays perl list perl-data-structures
基于此答案及其join陈述的最小代码
my @x = qw/10 20 30 40/;
my @y = qw/60 70 8 90 10/;
my @input_list = (@x, @y);
print "Before join @input_list \n";
print join ",", @$_ for @input_list ;
print "After join @input_list \n";
Run Code Online (Sandbox Code Playgroud)
这使
Before join 20 40 60 80 120 140 16 180 20
After join 20 40 60 80 120 140 16 180 20
Run Code Online (Sandbox Code Playgroud)
但在 use strict;
在test4.pl第10行使用"strict refs"时,不能使用字符串("10")作为ARRAY引用.
join在手动中连接单独的数组字符串.这里代码尝试使用@$_数组项的每个hash()显式连接逗号.然而,这似乎正在发生.
为什么这个错误出现在最小代码中?
好的,你在这做什么:
print join ",", @$_ for @input_list ;
Run Code Online (Sandbox Code Playgroud)
不工作,因为它是:
@input_list提取每个元素$_.$_假装它是一个数组@$_.这基本上与尝试:
print join ( ",", @{"10"} );
Run Code Online (Sandbox Code Playgroud)
这没有任何意义,因此不起作用.
my $string = join ( ",", @input_list );
print $string;
Run Code Online (Sandbox Code Playgroud)
会做的伎俩.
我想你在这里缺少的是这样的:
use Data::Dumper;
my @x = qw/10 20 30 40/;
my @y = qw/60 70 8 90 10/;
my @input_list = (@x, @y);
print Dumper \@input_list;
Run Code Online (Sandbox Code Playgroud)
不生成多维列表.这是一个单一的.
$VAR1 = [
'10',
'20',
'30',
'40',
'60',
'70',
'8',
'90',
'10'
];
Run Code Online (Sandbox Code Playgroud)
我怀疑你可能想要的是:
my @x = qw/10 20 30 40/;
my @y = qw/60 70 8 90 10/;
my @input_list = (\@x, \@y);
Run Code Online (Sandbox Code Playgroud)
也许:
my $x_ref = [ qw/10 20 30 40/ ];
my $y_ref = [ qw/60 70 8 90 10/ ];
my @input_list = ($x_ref, $y_ref );
Run Code Online (Sandbox Code Playgroud)
这使得@input_list:
$VAR1 = [
[
'10',
'20',
'30',
'40'
],
[
'60',
'70',
'8',
'90',
'10'
]
];
Run Code Online (Sandbox Code Playgroud)
然后你的'for'循环工作:
print join (",", @$_),"\n" for @input_list ;
Run Code Online (Sandbox Code Playgroud)
因为那时,@input_list实际上是2项 - 两个数组引用,然后您可以取消引用和连接.
尽管有一点警告 - 在做的时候可能会发生以下问题之一:
my @input_list = (\@x, \@y);
Run Code Online (Sandbox Code Playgroud)
因为您正在插入引用,@x并且@y- 如果您重复使用其中任何一个,那么您将更改内容@input_list- 这就是为什么使用它可能更好my @input_list = ( $x_ref, $y_ref );.
| 归档时间: |
|
| 查看次数: |
112 次 |
| 最近记录: |