List 比较两个单词列表,并在perl中保存不在第二个列表中的单词
我已经尽了一切努力,将一个文件中唯一存在的单词与另一个文件中的单词进行比较。我在代码中添加了一些调试打印,以找出它的去向,并发现代码在比较循环中从未执行任何操作 我觉得我是瞎子或者忽略了一些非常明显的事情——请有人指出什么是错的,并喜欢嘲笑我“可能是新手”的错误List 比较两个单词列表,并在perl中保存不在第二个列表中的单词,list,perl,compare,List,Perl,Compare,我已经尽了一切努力,将一个文件中唯一存在的单词与另一个文件中的单词进行比较。我在代码中添加了一些调试打印,以找出它的去向,并发现代码在比较循环中从未执行任何操作 我觉得我是瞎子或者忽略了一些非常明显的事情——请有人指出什么是错的,并喜欢嘲笑我“可能是新手”的错误 while(){#读取文件 咀嚼; $\uLC;#转换为小写 s//--/g;#删除双连字符破折号 s/-//g;#删除单连字符破折号 s//+//g;#用一个空格替换多个空格 删除标点符号 @hwords=拆分; #foreach$w
while(){#读取文件
咀嚼;
$\uLC;#转换为小写
s//--/g;#删除双连字符破折号
s/-//g;#删除单连字符破折号
s//+//g;#用一个空格替换多个空格
删除标点符号
@hwords=拆分;
#foreach$w(@hwords){print“$w\n”;}
}
当()读取文件时{#
咀嚼;
$\uLC;#转换为小写
s//--/g;#删除双连字符破折号
s/-//g;#删除单连字符破折号
s//+//g;#用一个空格重新显示多个空格
删除标点符号
@awords=拆分;
#foreach$w(@awords){print“$w\n”;}
}
$count=0;
@唯一=();
打印“到达这里!\n”;#是的,它到了
foreach$w(@hwords){print“$w\n”;}
每小时$h(@hwords){
$x=1;
打印“到达那里!\n”;#不,不到达这里
每个$a(@awords){
如果($h eq$a){
$x=0;
打印“等于”\n;#永远看不到这一点
}
}
如果($x等式1){
++$count;
@unique=@unique,$h;
打印“$count,$h\n”#也不要看到这个
}
}
首先,循环的每次迭代都会完全替换@hwords
和@awords
。因此,最后,@hwords
和@awords
将只包含每个文件最后一行中的单词
无论如何,你只需要从第一个文件中提取单词。然后,在读取第二个文件时,将其字与第一个文件中存储的字进行比较
因此,在第一个循环中,不要设置@hwords
,而是将其设置为查找哈希:
$hwords{$_} = 1 for split;
print "Word not found: $_\n"
for grep { !$hwords{$_} } split;
现在,在读取第一个文件后,它的所有字都是%hwords
散列的键
然后,在读取第二个文件时,在第二个循环中,在查找哈希中查找每个单词:
$hwords{$_} = 1 for split;
print "Word not found: $_\n"
for grep { !$hwords{$_} } split;
首先,循环的每次迭代都会完全替换
@hwords
和@awords
。因此,最后,@hwords
和@awords
将只包含每个文件最后一行中的单词
无论如何,你只需要从第一个文件中提取单词。然后,在读取第二个文件时,将其字与第一个文件中存储的字进行比较
因此,在第一个循环中,不要设置@hwords
,而是将其设置为查找哈希:
$hwords{$_} = 1 for split;
print "Word not found: $_\n"
for grep { !$hwords{$_} } split;
现在,在读取第一个文件后,它的所有字都是%hwords
散列的键
然后,在读取第二个文件时,在第二个循环中,在查找哈希中查找每个单词:
$hwords{$_} = 1 for split;
print "Word not found: $_\n"
for grep { !$hwords{$_} } split;
这是一个常见问题,可以在常见问题中找到解决方案
感谢irc.freenode.net上的@Botje on#perl提醒我这一点。这是一个常见问题,可以在常见问题中找到解决方案 感谢irc.freenode.net上的@Botje on#perl提醒我这一点。请检查:
use Array::Utils qw(:all);
my @a = qw( a b c d );
my @b = qw( c d e f );
#get items from array First list that are not in array Second List
my @notinsecond = array_minus( @b, @a );
#get items from array Second list that are not in array First List
my @notinfirst = array_minus( @a, @b );
print join "\n", @notinfirst;
print join "\n", @notinsecond;
请检查以下内容:
use Array::Utils qw(:all);
my @a = qw( a b c d );
my @b = qw( c d e f );
#get items from array First list that are not in array Second List
my @notinsecond = array_minus( @b, @a );
#get items from array Second list that are not in array First List
my @notinfirst = array_minus( @a, @b );
print join "\n", @notinfirst;
print join "\n", @notinsecond;
请注意,要正确显示代码,需要在编辑器窗口中将其缩进4个空格。我已经为您编辑了这篇文章。为了使缩进保持一致,我建议您也使用
perltidy
。请注意,要正确显示代码,您需要在编辑器窗口中将其缩进4个空格。我已经为您编辑了这篇文章。为了使缩进保持一致,我建议您也使用perltidy
。