Perl方式运行命令从一个数组获取输入并将输出放在另一个数组中

时间:2017-07-20 18:28:18

标签: perl

例如:

# Goal: Take the items in @input_array and sort them using the sort
#       app with the specified flags

# Partial code follows
my @input_array=('abc def 123','ghi jkl 456','mno pqr 789');
my @output_array=`sort -nrk3`; # The data fed to the stdin of sort should be
                              # @input_array with @output_array getting the sorted output
                              # per the command with the given flags

# Sure, we can dump @input_array to a temp file and use that as the input for sort, but
# I am hoping to avoid this.

3 个答案:

答案 0 :(得分:3)

array.map { |s| s.rjust(3, "0").chars.to_set }.
      include?(register.rjust(3, "0").chars.to_set)

my @output_array = sort { (split(' ', $b))[2] <=> (split(' ', $a))[2] } @input_array;

答案 1 :(得分:2)

use strict;
use warnings;

# custom comparison function for sort
sub sortie {
  # map input data $a, $b into data for comparison $A, $B (trailing numbers)
  my($A,$B) = map { /\s(\d+)$/ } ($a,$b);
  # compare $A and $B numerically returning reverse order
  # compare $a and $b string as fall-back (when $A and $B are equal)   
  return $B <=> $A || $a cmp $b;
}

# data/array to be sorted
my @input_array=('abc def 123','ghi jkl 456','mno pqr 789');
# sort array using sortie for comparison
my @output_array = sort sortie @input_array; 

# print/show sorted array
print "$_\n" for @output_array; 

答案 2 :(得分:-1)

perl - 使用外部程序(例如排序)将数组映射到数组

&#34; Pure perl&#34;对于问题中包含的样本数据,解决方案更好 有些人需要通过外部程序进行(重新)映射。

use strict;
use warnings;
use IPC::Run;

sub sortie {
  my ( $cmd, @input_array ) = @_;
  my $in = join( "\n", @input_array, '' );
  IPC::Run::run $cmd, \$in, \my $out, \my $err;
  return $out =~ /^(.*)$/mg;
} ## end sub sortie

my @input_array = ( 'abc def 123', 'ghi jkl 456', 'mno pqr 789' );
my @output_array = sortie( [ 'sort', '-nrk3' ], @input_array );
print "$_\n" for @output_array;