我已经学会了如何使用以下代码删除Perl中的重复项:
my %seen = ();
my @unique = grep { ! $seen{ $_}++ } @array;
Run Code Online (Sandbox Code Playgroud)
但是,如果我想合并重叠的部分呢?有没有像上面代码那样直接完成工作的简单方法?
例如,一些输入文件看起来像这样:
Anais Nin : People living deeply have no fear of death. Pascal : Wisdome sends us back to our childhood. Nietzsche : No one lies so boldly as the man who is indignant. Camus : Stupidity has a knack of getting its way. Plato : A good decision is based on knowledge and not on numbers. Anais Nin : We don't see things as they are, we see them as we are. Erich Fromm : Creativity requires the courage to let go of certainties. M. Scott Peck : Share our similarities, celebrate our differences. Freud : The ego is not master in its own house. Camus : You cannot create experience. You must undergo it. Stendhal : Pleasure is often spoiled by describing it.
欲望输出如下:
Anais Nin : People living deeply have no fear of death. We don't see things as they are, we see them as we are. Pascal : Wisdome sends us back to our childhood. Nietzsche : No one lies so boldly as the man who is indignant. Camus : Stupidity has a knack of getting its way. You cannot create experience. You must undergo it. Plato : A good decision is based on knowledge and not on numbers. Erich Fromm : Creativity requires the courage to let go of certainties. M. Scott Peck : Share our similarities, celebrate our differences. Freud : The ego is not master in its own house. Stendhal : Pleasure is often spoiled by describing it.
一如既往地感谢您的任何指导!
小智 7
这是正则表达式和哈希的一个非常简单的应用.我将您的数据放入名为"merge.txt"的文件中.这会将结果打印到标准输出.
#! perl
use warnings;
use strict;
open my $input, "<", "merge.txt" or die $!;
my %name2quotes;
while (my $line = <$input>) {
if ($line =~ /(.*?)\s*:\s*(.*?)\s*$/) {
my $name = $1;
my $quote = $2;
if ($name2quotes{$name}) {
$name2quotes{$name} .= " " . $quote;
} else {
$name2quotes{$name} = $quote;
}
} # You might want to put an "else" here to check for errors.
}
close $input or die $!;
for my $name (sort keys %name2quotes) {
print "$name : $name2quotes{$name}\n";
}
Run Code Online (Sandbox Code Playgroud)