如果我有@array
一行:
row 1: a b
row 2: b c
row 3: c d
我如何获得@array2
一列中所有元素的新元素,所以@array2 = a b b c c d
?
谢谢!
如果我有@array
一行:
row 1: a b
row 2: b c
row 3: c d
我如何获得@array2
一列中所有元素的新元素,所以@array2 = a b b c c d
?
谢谢!
您的问题措辞有些含糊,这可能是因为您是 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";
}
对初始数据的另一种可能解释是您有一个数组引用数组。这个“看起来”像一个二维数组,因此你会谈论“行”。如果是这种情况,那么试试这个
#!/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;
这是另一种选择:
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
.
my @array_one = (1, 3, 5, 7);
my @array_two = (2, 4, 6, 8);
my @new_array = (@array_one, @array_two);