perl 两个数组 合并成一个新数组 按行分别对齐 按关键词计算差值

2024-11-16 07:56:13
推荐回答(2个)
回答1:

#!/usr/bin/env perl
use strict;

open( my $fh1, '<', 'file1' ) or die $!; 
open( my $fh2, '<', 'file2' ) or die $!; 

my @one = grep { not /Time/ } <$fh1>;
my @two = grep { not /Time/ } <$fh2>;
my %three = map{ 
 运弯                 my ($t2, $d2) = (/(\S+)\s+(\S+)/);
                  my ($t1, $d1) = (shift(@one) =~ /(\S+)\s+(\S+)/);
                  $d2 => $t2-$t1
} @two;

printf( "%-5s\t%-8s\n", 'Time', 'Data');
for my $key (keys %three) {
  printf( "%-5s\t%-8s\n"启橘, $three{$key}, $key );
}
close $fh1;
close $fh2;

 

我来补充一下,你的”如果没有相同的值,就从@one的下旁旁闷一行寻找“是指哪个没有相同的值, 是Data吗? 

回答2:

#! /usr/bin/perl

open SRC_FILE_1, "data_1" or die "cann't open data_1";
open SRC_FILE_2, "data_2" or die "cann't open data_2";
my @one = 拍高脊;
my @two = ;
my $length = ( @one > @two ) ? scalar @one : scalar @two;
my @three;
for my $idx (0..($length-1)){
chomp($one[$idx]);
chomp($two[$idx]);
$three[$idx] = sprintf "%-30s %s \n", $one[$idx], $two[$idx];
}
open DEST_FILE, "> data_3" or die "cann't open output";
for my $line (@three){
print DEST_FILE $line;
}
my %one = &list_2_hash(@one);
my %two = &list_2_hash(@two);
open DIFF_FILE, "> diff_result" or die "cann't open diff_result";
printf DIFF_FILE ("%-12s %s\袭渗n", "Time", "Data");
for (keys %one){
if(defined($two{$_})){
my $diff_value = $two{$_} - $one{$_};
printf DIFF_FILE ("%-12s %s\n", "$diff_value", "念拦$_")
}
}
sub list_2_hash{
my @list = @_;
#print @list;
my %hash;
for (@list){
next if /Time/;
chomp($_);
my ($value, $key) = split /\s+/, $_;
$hash{"$key"} = $value;
}
return %hash;
}