开发者

Update the perl script to include number of times the row is repeated

开发者 https://www.devze.com 2023-03-16 01:42 出处:网络
I have below a perl script which gives a list of entries which are present more than once in a file/STDIN.

I have below a perl script which gives a list of entries which are present more than once in a file/STDIN. I want to update this script so that it also shows how many times the entries have been repeated.

#!/usr/bin/perl

use strict;
use warnings;

my %duplicates;

while (<>) {
  chomp;
  $duplicates{$_}++;
}

foreach my $key (keys %duplicates) { 
  if ($duplicates{$key} > 1) {
    delete 开发者_开发问答$duplicates{$key}; 
    print "$key\n";
  }
}


The delete builtin returns the value deleted. So you can use:

print "$key: ", delete $duplicates{$key}, "\n";


You can print $duplicates{$key} while iterating on keys:

#!/usr/bin/perl

use strict;
use warnings;

my %duplicates;

while (<>) {
  chomp; 
  $duplicates{$_}++;
}

foreach my $key (keys %duplicates) { 
  if ($duplicates{$key} > 1) {
       print "$key is repeated $duplicates{$key} times\n";
       delete $duplicates{$key}; 
  }
}


Just print $duplicates{$key}. Or am I missing something?

Also, are you sure you need to delete $duplicates{$key}?

0

精彩评论

暂无评论...
验证码 换一张
取 消