问题描述:

I'm using this code to remove all duplicates, but I have a need to remove only specific duplicates and leave all others untouched.

In my case if the line matches /^\s+INDEX 00 \d\d:\d\d:\d\d$/ then keep each unique first line, but delete duplicates, and keep all lines that don't match the regex.

tie my @lines, 'Tie::File', $fn or die "could not tie file: $!";

my %seen;

@lines = grep(!$seen{$_}++, @lines);

untie @lines;

网友答案:
tie my @lines, 'Tie::File', $fn or die "could not tie file: $!";
my %seen;
@lines = grep(!/^\s+INDEX 00 \d\d:\d\d:\d\d$/ || !$seen{$_}++, @lines);
untie @lines;
网友答案:
@lines = ( $array[0],
             grep { not /^\s+INDEX 00 \d\d:\d\d:\d\d$/ } @lines[1..$#lines] );

Explanation

  • An array slice is taken to ignore the first element while filtering with grep
  • grep filters through all elements that don't match the regex
  • The resultant array is assigned to @lines
相关阅读:
Top