Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Re: How to make buckets of like data

by roboticus (Chancellor)
on Feb 05, 2013 at 23:40 UTC ( #1017303=note: print w/replies, xml ) Need Help??

in reply to How to make buckets of like data


That was amusing.

$ cat #!/usr/bin/perl use strict; use warnings; my %Grps; # Build the groups while (<DATA>) { my ($l,$r) = split /\s*,?\s+/, $_; last unless defined $r; my $gl = $Grps{$l}; my $gr = $Grps{$r}; if (defined $gl) { if (defined $gr) { if ($gr != $gl) { # Merge two groups my %new_gr = map { $_=>0 } @$gr, @$gl; my $new_gr = [ sort keys %new_gr ]; $Grps{$_} = $new_gr for @$new_gr; } } else { # Add $r existing group push @{$Grps{$r}=$gl},$r; } } elsif (defined $gr) { # Add $l to existing group push @{$Grps{$l}=$gr},$l; } else { # Create new group my $new_gr = [ $l, $r ]; $Grps{$_} = $new_gr for @$new_gr; } } #...and print them for my $K (keys %Grps) { next unless @{$Grps{$K}}>0; print "{ ", join(", ", splice @{$Grps{$K}}), " }\n"; } __DATA__ A, B C, D A, C E, F F, G $ perl { E, F, G } { A, B, C, D }

I did a similar version using hashes, but I think this one is a little better. (Perhaps I could've said it better as "the hash one was a little uglier".)

Update: I prefer Browser's version because it has better notation. I prefer the concept of mine, but can't figure out how to make the notation as nice as his...


When your only tool is a hammer, all problems look like your thumb.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1017303]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2018-06-20 02:42 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (116 votes). Check out past polls.