in reply to Re: duplicate lines in array
in thread duplicate lines in array

A bit of golfing. :-)

use strict; use warnings; my @rec = ( 'N(8) -- H(15) .. O(9)', 'N(8) -- H(15) .. N(8)', 'N(8) -- H(16) .. O(9)', ); my %count; for (@rec) { /(H\(\d+\))/ && do { push @{$count{$1}}, $_ } } for (keys %count) { if ($#{$count{$_}}) { print "$_\n" for @{$count{$_}} } } __END__ # another go... $,="\n"; for (keys %count) { print @{$count{$_}} if $#{$count{$_}} }


Replies are listed 'Best First'.
Re: Re: Re: duplicate lines in array
by Skeeve (Parson) on Jan 23, 2004 at 14:30 UTC
    If you want to golf you may increase yout handicap by shortening
    for (@rec) { /(H\(\d+\))/ && do { push @{$count{$1}}, $_ } } for (keys %count) { if ($#{$count{$_}}) { print "$_\n" for @{$count{$_}} } }
    to just
    /(H\(\d+\))/ && push(@{$count{$1}},$_."\n") for (@rec); print map @{$count{$_}},grep $#{$count{$_}},keys %count;
    Anyone volunteering to explain my code?
      Another go... ;-)

      /(H\(\d+\))/,push@{$count{$1}},"$_\n"for@rec; print map{$#{$count{$_}}?@{$count{$_}}:''}keys%count;

      Bah, you call that golfing? :) You used multi-letter variable names and more than one space.

      /(H\(\d+\))/&&push@{$c{$1}},"$_\n"for@r; print map@{$c{$_}},grep$#{$c{$_}},keys%c;
        How comes you missed this?
        /H\(\d+\)/&&push@{$c{$&}},$_.$/for@r;
        You could even save "keys" because no value will be a key:
        print map@{$c{$_}},grep$#{$c{$_}}>0,%c;