档案1
word1 word2 word3
word1 word4 word2
word2 word4 word2
文件2
word1 word8 word5....
我想要的结果是如果文件2中存在单词,则从文件1中添加单词的所有下一个单词。添加的每个单词都应该添加一次。
所以resulat
word1 word2 word3 word4 word8 word5....
我试试这个,但它没有给我解决方案
#!/usr/bin/perl
open FILE1,"./fichier1.txt" or die "Cannot open fichier1.txt";
open FILE2,"./fichier2.txt" or die "Cannot open fichier2.txt";
open FILE3,">./resultat.txt" or die "Cannot create resultat.txt";
while (<FILE1>)
{
chomp;
/[^\ ]*$/;
$common = $&;
$begin = $`;
chop $begin;
$array{$common} = $begin;
}
close FILE1;
while (<FILE2>)
{
chomp;
/^[^\ ]*\ /;
$common = $&;
chop $common;
$end = $';
print FILE3 "$array{$common} $common $end\n" if exists $array{$common};
}
close FILE2;
close FILE3;
答案 0 :(得分:1)
open $FILE1,'<','./fichier1.txt' or die "Cannot open fichier1.txt $!";
open $FILE2,'<','./fichier2.txt' or die "Cannot open fichier2.txt $!";
open $FILE3,'>', './resultat.txt' or die "Cannot create resultat.txt $!";
my %unique;
my @result;
sub pusher {
for (split /\s+/, shift) {
next unless $_;
next if ($unique{$_});
push @result, $_;
$unique{$_} = 1;
}
}
for(<$FILE1>, <$FILE2>) {
pusher($_);
}
close($FILE1);
close($FILE2);
print $FILE3 join ' ', @result;
close($FILE3);
答案 1 :(得分:0)
您想要将文件1中的所有单词(文件2中的所有单词)写入文件3,并且仅执行一次吗?
这会对你有所帮助
open my $FILE1,"<","./fichier1.txt" or die "Cannot open fichier1.txt $!";
open my $FILE2,"<","./fichier2.txt" or die "Cannot open fichier2.txt $!";
open my $FILE3,">", "./resultat.txt" or die "Cannot create resultat.txt $!";
my %unique;
while(<$FILE2>) {
my @words = split /\s/;
$unique{$_} = 1 for @words;
}
close($FILE2);
while(<$FILE1>) {
my @words = split /\s/;
for (@words) {
if ($unique{$_}) {
print $FILE3 "$_ ";
delete $unique{$_};
}
}
}
这是我的fichier1.txt
word1 word2 word3
word1 word5 word9
word2 word4 word8
这是我的fichier2.txt
word1 word8 word5 word10
这是我的result.txt
word1 word5 word8
也许我没有正确理解任务