我有一个数组@foo,其中包含以下条目
Database alias = SAMPLE1
Database alias = SAMPLE2
Database alias = SAMPLE3
现在我只想要第三列,即
样品1
样品2
样品3
我可以在 shell 中使用awk (awk '{print $3}'),我如何在 perl 中做到这一点?
我有一个数组@foo,其中包含以下条目
Database alias = SAMPLE1
Database alias = SAMPLE2
Database alias = SAMPLE3
现在我只想要第三列,即
样品1
样品2
样品3
我可以在 shell 中使用awk (awk '{print $3}'),我如何在 perl 中做到这一点?
awk '{print $3}' < data.txt
给出=符号,你的意思是4美元
然而,在 perl 中,自动拆分数组从零开始,所以它是 3
perl -lane 'print $F[3]' < data.txt
如果你想要第 n 列空格分隔的字符串,这就是如何做到这一点的想法:
#!/usr/bin/env perl
use strict;
use warnings;
my @foo = ( "Col1 Col2 Col3 Col4", # This is
"Row2 R2C2 Row2C3 Row2C4" ); # the input array.
my $n = 2; # We want to select the 3rd column.
my @nth_columns;
for my $row (@foo) { # We go through the input array,
my @columns = split /\s+/, $row; # splitting each row by whitespaces
push @nth_columns, $columns[$n]; # and adding the n-th column to output array
}
你当然可以用许多更短的方式来写。我最喜欢的应该是这样的:
my @third_columns = map { (split /\s+/)[2] } @foo;