【问题标题】:Matching matrix in perl or bashperl 或 bash 中的匹配矩阵
【发布时间】:2013-07-26 14:16:51
【问题描述】:

我想知道您是否可以帮我找到解决问题的方法(不必给我代码)。 我想在 perl 或 Bash 中创建一个“匹配矩阵”。

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

ID1 
ID4 
ID20 
ID1 

为了让我的生活更轻松,我的第二个文件只是一个带有多个 ID (file2) 的长行

ID1 ID2 ID3 ID4 .... IDn

我想实现这个输出:

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

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

任何帮助,提示都非常感谢。

【问题讨论】:

  • The tricky part for me is... 您能否为不那么棘手的部分发布代码?这样我们就可以专注于特定的问题,而不必从头开始实施一切。
  • 这不是微不足道的吗?只需将两个列表保存在一个数组中,打印一个标题,然后在两个数组上创建一个嵌套循环并在键匹配时打印 X。
  • 所以@TLP 做了你要求的——give me a hand。现在回答您自己的问题并获得Self-Learner 徽章!
  • 谢谢 TLP。我正在做。不知道为什么我将 file2 存储到哈希中。我现在就试试这个数组。

标签: bash perl matrix match


【解决方案1】:

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

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";
    }
}

【讨论】:

  • 你已经掉入了使用|| 而没有open 括号的陷阱。你的die 声明永远不会发生。阅读perldoc perlop 中的优先级列表,您就会明白为什么。当您可能打算在 ' ' 上拆分时,您也在单个空格上进行拆分,以避免在连续空格上创建空字段。
  • ' '/\s+/ 在 split 中的唯一区别是前者会按照您的想法执行并去除前导空格。所以你几乎总是想要那个。如果您想在 while 循环中使用命名变量,只需执行 while (my $id = &lt;FILE1&gt;).. 当然,您应该始终使用三个参数打开和词法文件句柄。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-18
  • 2018-01-21
相关资源
最近更新 更多