【发布时间】:2012-03-13 10:18:52
【问题描述】:
我想读入带有“!”等符号的文件和“^”,并想在我将它们与另一行的其他字符串进行比较之前删除它们。如果删除符号后两个字符串相同,我想将它们存储在另一个名为“common”的哈希中。 例如... 文件A:
hello!world
help?!3233
oh no^!!
yes!
文件B:
hello
help?
oh no
yes
在这种情况下,FileA 和 FileB 应该是相同的,因为我正在比较字符直到“!”所在的位置或出现“^”。 我使用以下代码读取文件:
open FILEA, "< script/".$fileA or die;
my %read_file;
while (my $line=<FILEA>) {
(my $word1,my $word2) = split /\n/, $line;
$word1 =~ s/(!.+)|(!.*)|(\^.+)|(\^.*)//;#to remove ! and ^
$read_file{$word1} = $word1;
}
close(FILEA);
我打印出散列中的键,它显示了正确的结果(即,它将 FileA 转换为“你好,帮助?哦,不,是的)。但是,当我使用以下方法比较 FileA 和 FileB 时代码,总是失败。
while(($key,$value)=each(%config))
{
$num=keys(%base_config);
$num--;#to get the correct index
while($num>=0)
{
$common{$value}=$value if exists $read_file{$key};#stored the correct matches in %common
$num--;
}
}
我尝试使用以下示例测试我的替换和比较 2 个字符串,它有效。我不知道为什么它不能从文件中读取字符串到哈希中。
use strict;
use warnings;
my $str="hello^vsd";
my $test="hello";
$str =~ s/(!.+)|(!.*)|(\^.+)|(\^.*)//;
my %hash=();
$hash{$str}=();
foreach my $key(keys %hash)
{
print "$key\n";
}
print "yay\n" if exists $hash{$test};
print "boo\n" unless exists $hash{$test};
两个文件的文本行数可以不同,搜索时文本行的顺序不必相同。 IE。 "oh no" 可以出现在 "hello" 之前。
【问题讨论】:
-
你能假设文件 A 中的每一行只应与文件 B 中的相应行进行比较吗?并且文件 A 和文件 B 的行数相等?
-
没有。 FileA 和 FileB 可以有不同的行数,并且行的顺序不必相同。