【发布时间】:2015-06-08 13:58:23
【问题描述】:
我是 Perl 的初学者,我正在尝试编写一个脚本来比较两个散列并打印第一个散列中没有在第二个散列中找到的值。尽管我知道脚本应该非常简单,但我不确定为什么我的脚本不起作用。任何帮助将非常感激。
到目前为止我的脚本:
#!/usr/bin/perl
use strict;
use warnings;
use vars qw($a $b $c $d $hash1 %hash1 $info1 $hash2 %hash2);
open (FILE1, "<file1.txt") || die "$!\n Couldn't open file1.txt\n";
while (<FILE1>){
chomp (my $line=$_);
my ($a, $b, $c, $d) = split (/\t/, $line);
if ($a){
$hash1 -> {$a} -> {info1} = "$b\t$c\t$d";
}
$info1=$hash1->{$a}->{info1};
}
open (FILE2, "<file2.txt") || die "$!\n Couldnt open file2.txt \n";
open (Output, ">Output.txt")||die "Can't Open Output file";
while (<FILE2>) {
chomp (my $line=$_);
my ($a, $b, $c, $d) = split (/\t/, $line);
if ($a){
$hash2 -> {$a} -> {info2} = "$b\t$c\t$d";
}
foreach (my $hash1->{$a}) {
if (!exists $hash2{$a}) {
print Output "$a\t$info1\n";
}
}
}
close FILE1;
close FILE2;
close Output;
print "Done!\n";
【问题讨论】:
-
拥有同名的不同变量(除了印记),如
%hash1和$hash1只会让你伤心。 -
这个小脚本中有大量的不良做法。我强烈推荐阅读 Perl 最佳实践 以避免使用 Perl 的许多陷阱。在这个时候学习 Perl 没有必要养成坏习惯。
-
特别是,强烈建议不要使用
use varspragma。此外,我们看不到您的输入文件是什么。因此,很难判断您的程序要做什么。