这就是我的情况。我有两张桌子:
Table 1
C0 C1 C2 C3 ... C8
1 10
2 50
3 70
3 20
Table 2
C0 C1 C2 C3 ... C7
1
2
3
Table 2 should become like this
C0 C1 C2 C3 ... C7
1 x = 10
2 x = 50
3 x = 70,20
基本上我想要做的是比较两个表的C1值。如果值相同,则应将C8(表1)的值复制到C7(表2),并添加“x =”。但是当C1(table1)中存在重复值时,就像这里的3一样,那么在表2中这些值应该彼此相邻,分别用','(就像这里x = 70,20)
这是我到目前为止所拥有的
my $table1 = $ARGV[0];
my $table2 = $ARGV[1];
# Open my file (I use exactly the same code for opening table 2)
unless ($table1) {
print "Enter filename of file:\n";
$table1 = <STDIN>;
chomp $table1;
}
open(DATA1,'<',$table1) or die "Could not open file $filename $!";
# Here I push the values of C8 in table 1 to the same row
my %info = ()
while (<DATA1>) {
my @columns = split;
if( exists $info{ $columns[1] } ) {
push @{ $info{ $columns[1] }->{var} }, $columns[8];
}
else {
$info{ $columns[1] } = { var =>[ $columns[8] ] }
}
}
如果这一切都正确,我现在唯一需要做的就是将值复制到C7(表2)并让它们以“x =”开头
有人可以帮我这个吗?
答案 0 :(得分:1)
我认为这就是你要求的。有关如何在%t1中访问@line的详细信息,请参阅perldoc perldsc
和perldoc perllol
use strict;
use warnings;
my $table1 = $ARGV[0];
my $table2 = $ARGV[1];
open(my $fh1,$table1) || die "$! $table1";
open(my $fh2,$table2) || die "$! $table1";
#discard the first lines which are the headers
my $headers1=<$fh1>;
my $headers2=<$fh2>;
#set up data from table1
my %t1=();
while(<$fh1>) {
chomp; #remove newlines
my @line=split(/\t/); #split on tabs
my $keyfield=$line[1]; #key is C1
push @{$t1{$keyfield}}, $line[8];
}
#read from table2 and write output
while(<$fh2>) {
chomp; #remove newlines
my @line=split(/\t/); #split on tabs
my $keyfield=$line[1]; #key is C1
my @x=();
if (exists($t1{$keyfield}) ) {
push @x,@{$t1{$keyfield}}; # get the C8 values from t1
}
for my $c (0..6) {
print $line[$c],"\t"; #print C0 to C6 with a tab seperator
}
print "x = ",join(",",@x),"\n"; #do x=70,20
}
答案 1 :(得分:0)
您正在尝试将数组引用映射到字符串中!
你能做的是,
$string
。$string
连接为$string = "x = $string";
。$string
分配给哈希(%info
)以代替array reference
。 Sice都是标量,任务应该不是问题。