
[英]How can I find elements that are in one array but not another in Perl?
[英]how do i put array elements from one array into another in perl?
如果我有一个带有行的@array
:
row 1: a b
row 2: b c
row 3: c d
如何获得一个包含一列中所有元素的新@array2
,所以@array2 = abbccd
?
谢谢!
你的问题有点含糊不清,这可能是因为你是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";
}
my @array_one = (1, 3, 5, 7);
my @array_two = (2, 4, 6, 8);
my @new_array = (@array_one, @array_two);
这是另一种选择:
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
的新列表。
对初始数据的另一种可能解释是,您有一个数组引用数组。 这看起来像一个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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.