in reply to Sorting a list and removing duplicate elements

#!/usr/bin/perl use strict; use warnings; my %data; while (<DATA>) { chomp; next unless /\S/; my ($name, $num) = /(.*)\s+(\d+)/; push @{$data{$name}}, $num if ($name && $num); } foreach my $name (sort keys %data) { print "$name "; print join ',', sort { $a <=> $b } @{$data{$name}}; print "\n\n"; } __END__ Chee S. L. 8 Cheng T. H. 5 Cheng T. H. 2 Chetan M. 4
--
<http://www.dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re: Sorting a list and removing duplicate elements
by Anonymous Monk on Aug 17, 2004 at 16:55 UTC
    wonderful, your code does the magic

    thank you very much

Re^2: Sorting a list and removing duplicate elements
by texuser74 (Monk) on Aug 19, 2004 at 10:29 UTC

    Thank you for your help, but one more difficulty i have

    how to remove the duplicate numbers, e.g.

    Cheng T. H. 2,2,5
    Chetan M. 4

    this one should be as

    Cheng T. H. 2,5
    Chetan M. 4

    i.e. here i want to remove 2 from first entry

    Thanks in advance

      Change ${data}{$name} to be a hash instead of an array.

      #!/usr/bin/perl use strict; use warnings; my %data; while (<DATA>) { chomp; next unless /\S/; my ($name, $num) = /(.*)\s+(\d+)/; $data{$name}{$num} = 1; } foreach my $name (sort keys %data) { print "$name "; print join ',', sort { $a <=> $b } keys %{$data{$name}}; print "\n\n"; } __END__ Chee S. L. 8 Cheng T. H. 5 Cheng T. H. 2 Chetan M. 4 Cheng T. H. 2
      --
      <http://www.dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg