2013-07-26 35 views
0

我想知道如果你能给我一只手来找到解决方案(而不是必须给我一个代码)来解决我的问题。 我想在perl或Bash中创建一个“匹配矩阵”。perl或bash中的匹配矩阵

基本上,我的第一个文件是ID的提取列表,而不是唯一的(文件1)

ID1 
ID4 
ID20 
ID1 

使我的生活更方便我的第二个文件是只是倍数的ID(文件2)

长线

ID1 ID2 ID3 ID4 .... IDn的

我想实现这样的输出:

ID1 ID2 ID3 ID4 ID5 ID6 ID7 .... ID20 IDn 
ID1 X 
ID4    X 
ID20         X 
ID1 X 

对我来说,棘手的部分是在找到匹配项时添加“X”。

任何帮助,提示都不胜感激。

+3

'对我来说最棘手的部分是......'你能不能张贴不那么棘手的部分代码?所以我们可以专注于具体问题而不必从头开始实施所有的事情。 –

+2

这难道不是微不足道的吗?只需将两个列表保留在数组中,打印一个标题,然后在两个数组上创建一个嵌套循环,并在键匹配时打印X. – TLP

+0

所以@TLP做了你所要求的 - “给我一只手”。现在回答你自己的问题,并获得[Self-Learner](http://stackoverflow.com/help/badges/14/self-learner)徽章! – devnull

回答

0

这是我对这个问题的答案:

use warnings; 
use strict; 

open(FILE1, "file1") || die "cannot find file1"; 
open(FILE2, "file2") || die "cannot find file2"; 

#read file2 to create hash 
my $file2 = <FILE2>; 
$file2 =~ s/\n//; 
my @ids = split(/\s+/, $file2); 
my %hash; 
my $i = 1; 
map {$hash{$_} = $i++;} @ids; 

#print the first line 
printf "%6s",''; 
for my $id (@ids) { 
    printf "%6s", $id; 
} 
print "\n"; 

#print the other lines 
while(<FILE1>) { 
    chomp; 
    my $id = $_; 
    printf "%6s", $id; 
    my $index = $hash{$id}; 
    if ($index) { 
     $index = 6 * $index; 
     printf "%${index}s\n",'x'; 
    } else { 
     print "\n"; 
    } 
} 
+1

你已经陷入了使用'||'的陷阱,并且没有为'open'使用括号。你的'死'声明永远不会发生。阅读'perldoc perlop'中的优先顺序列表,你会明白为什么。当你可能打算在''''上分割时,你也在分割一个空格,以避免在连续空格上创建空字段。 – TLP

+0

谢谢@TLP,现在呢? – walker

+0

split中''''和'/ \ s + /'的唯一区别就在于前者完成了你的想法并去掉了前导空格。所以你几乎总是想要那个。如果你想在while循环中使用一个命名变量,只要'while(my $ id = )'..当然,你应该总是使用三个参数打开和词法文件句柄。 – TLP