我有两个表。如果满足某个条件,我想将值从一个文件复制到另一个文件。这就是所有东西的样子
表1C1 C2 C3
1 a b
3 e f
表2 C1 C2 ... ... C7 C8 ...
1
2
3
表2应该变成这样:
C1 C2 ... ... C7 C8 ...
1 x=b
2
3 x=f
所以如果C1 (table1)和C2 (table2)的值相同,那么表1中C3的值应该放在表2的C8列中。C8中的新值都应该以"x="开头,后面跟着表1中的相应值
这是目前为止我用来打开数据的脚本
my $data1 = $ARGV[0];
my $data2 = $ARGV[1];
unless ($data1) {
print "Enter filename:n";
$data1 = <STDIN>;
chomp $data1;}
open(DATA1,'<',$data1) or die "Could not open file $filename $!";
unless ($data2) {
print "Enter filename:n";
$data2 = <STDIN>;
chomp $data2;}
open(DATA2,'<',$data2) or die "Could not open file $filename $!";
while (<DATA1>) {
my @columns = split /s+/;
next if /^s*C/;
# I'm doing some transformations here so that my input DATA1 has the format of table 1 in my example
}
foreach $c1(sort {$a<=>$b} keys %info ) {
print $c1, "t",
join(',',@{$info{$c1}->{variant}}), "t",
join(',',@{$info{$c1}->{frequency}}), "n";
# so $c1 is actually how table 1 in my example looks like
}
my %hash;
while($c1){
my @columns = split;
$hash{$columns[0]} = [$columns[2]];
}
while (<DATA2>) {
my @columns = split;
$columns[7] = @{ $hash{ $columns[0] } }[2] if exists $hash{ $columns[0] };
print "t", join (@columns), "n";
}
这是提供解决方案@choroba的脚本。然而,一定是出了什么问题,因为我在屏幕上没有得到任何输出。
和我怎么能添加语句"x="时复制的值?
使用散列来记住第一个文件
#!/usr/bin/perl
use warnings;
use strict;
use feature qw(say);
my ($data1, $data2) = @ARGV;
open my $T1, '<', $data1 or die $!;
my %hash;
while (<$T1>) {
my @fields = split;
$hash{$fields[0]} = [ @fields[ 1, 2 ] ];
}
open my $T2, '<', $data2 or die $!;
while (<$T2>) {
my @fields = split;
@fields[1, 2] = @{ $hash{ $fields[0] } }[0, 1] if exists $hash{ $fields[0] };
say join "t", @fields;
}
您可以对第一个文件使用散列来完成此操作:
my %columns1;
while (<DATA1>) {
my @c = split /s+/;
$columns1{$c[0]} = [ @c ];
next if /^s*C/;}
my %columns2;
while (<DATA2>) {
my @c = split /s+/;
if (defined $columns1{$c[0]}) {
$c[1] = $columns1{$c[0]}[1];
$c[2] = $columns1{$c[0]}[2];
}
$columns2{$c[0]} = [ @c ];
}