如果我有@array
行:
row 1: a b
row 2: b c
row 3: c d
如何获取包含一列中所有元素的新@array2
,所以@array2 = a b b c c d
?
谢谢!
答案 0 :(得分:2)
你的问题有点含糊不清,这可能是因为你是perl的新手。你没有用perl语法提供输入或预期输出,但根据你对先前答案的回答,我会猜测:
## three rows of data, with items separated by spaces
my @input = ( 'a b', 'b c', 'c d' );
## six rows, one column of expected output
my @expected_output = ( 'a', 'b', 'b', 'c', 'c', 'd' );
将其用于预期的输入和输出,编码转换的一种方法是:
## create an array to store the output of the transformation
my @output;
## loop over each row of input, separating each item by a single space character
foreach my $line ( @input ) {
my @items = split m/ /, $line;
push @output, @items;
}
## print the contents of the output array
## with surrounding bracket characters
foreach my $item ( @output ) {
print "<$item>\n";
}
答案 1 :(得分:0)
my @array_one = (1, 3, 5, 7);
my @array_two = (2, 4, 6, 8);
my @new_array = (@array_one, @array_two);
答案 2 :(得分:0)
这是另一种选择:
use Modern::Perl;
my @array = ( 'a b', 'b c', 'c d' );
my @array2 = map /\S+/g, @array;
say for @array2;
输出:
a
b
b
c
c
d
map
在@array
的列表中运行,将正则表达式(匹配非空格字符)应用于其中的每个元素,以生成放入@array2
的新列表。
答案 3 :(得分:0)
对初始数据的另一种可能解释是,您有一个数组引用数组。这看起来像一个2D数组,因此你会谈论“行”。如果是这种情况,那么试试这个
#!/usr/bin/env perl
use warnings;
use strict;
my @array1 = (
['a', 'b'],
['b', 'c'],
['c', 'd'],
);
# "flatten" the nested data structure by one level
my @array2 = map { @$_ } @array1;
# see that the result is correct
use Data::Dumper;
print Dumper \@array2;