0

我有两张桌子。如果满足某个条件,我想将值从一个文件复制到另一个文件。这就是一切的样子

表格1

C1    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=”?

4

2 回答 2

2

使用哈希来记住第一个文件。

#!/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;
}
于 2013-04-17T15:07:57.240 回答
0

您可以对第一个文件使用哈希来执行此操作:

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 ];
}
于 2013-04-17T15:10:02.267 回答