Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a problem grouping an array similar to SQL's GROUP BY. I need to group them by the first column. Arrays before and after:
before: 1 0 1 1 2 0 3 1 4 3 4 6 ------ after: 1 0-1 2 0 3 1 4 3-6
Any ideas? Thanks.

Replies are listed 'Best First'.
Re: Group 2d array
by gjb (Vicar) on Jan 05, 2003 at 17:11 UTC

    Given the data is ordered as you show, this should do what you want:

    my %data; while (<DATA>) { chomp($_); my ($first, $second) = split(/\s+/, $_); push(@{$data{$first}}, $second); } foreach my $first (sort {$a <=> $b} keys %data) { print "$first ", join('-', @{$data{$first}}), "\n"; }

    Hope this helps, -gjb-

(jeffa) Re: Group 2d array
by jeffa (Bishop) on Jan 05, 2003 at 17:14 UTC
    use strict; use warnings; my %thingy; while (<DATA>) { chomp; my ($index,$value) = split; push @{$thingy{$index}}, $value; } for (sort keys %thingy) { print "$_ ", join('-',@{$thingy{$_}}), "\n"; } __DATA__ 1 0 1 1 2 0 3 1 4 3 4 6

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: Group 2d array
by nandeya (Monk) on Jan 05, 2003 at 18:58 UTC
    Always more than one way to skin a cat.
    Here's another simple way.

    #!/usr/bin/perl -w use strict; my %gbhash; open(DATA, '/usr/local/fun/data.txt') or die $!; while (<DATA>) { chomp; my ($key,$val) = split; if (exists $gbhash{$key}) { $gbhash{$key} = $gbhash{$key} . '-' . $val; } else { $gbhash{$key} = $val; } } close DATA; #Now print em foreach my $skey (sort {$a<=>$b} keys %gbhash) { print "$skey $gbhash{$skey}\n"; } ------ DATA (data.txt): 1 0 1 1 2 0 3 1 4 3 4 6

    nandeya