[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Merging elements



On 12.10.00 at 16:59, Pete Prodoehl <pete.prodoehl@cygnusinteractive.com> wrote:

>I've tried doing this with a hash containing arrays, two separate arrays,
>and some other methods that were even more ineffective. My head is
>starting to hurt... There's probably some simple way to do this, I just
>can't figure it out...
>
>  aaa  438287,3231
>  aaa  10878,8678666
>
>where 'aaa' is a key appearing twice, and the two separate pieces of data
>(438287,3231 and 10878,8678666) need to be combined into one single piece
>of data, represented by aaa, so I'm trying to get the outcome to be:
>
>  aaa  438287,3231,10878,8678666

Well, Ronald's solution is much simpler, but accoring to "more then one
way..." etc. here is a solution that shows what's going on and shows you
the data structures. I'd assumed you wanted an actual list and not a string
with commas in it. :-)

If you want to get _really_ nasty, I'm sure there is some way to apply the
Schwartzian Transform to this. :-)

#!perl -w

use strict;
use vars qw(%Keys @Data %Result); # Shut -w up. :-)

# Loop over input, splitting on whitespace. Pre-populate the hash that
# will store the final datastructure with anon array refs. Finally store
# away both key and value in an array.
while (<DATA>) {
  my($k, $v) = split /\s+/, $_;
  $Result{$k} = []; # Creates uniqueness: second 'aaa' kills the first.
                    # Equivalent to the $Hash{'key'}++ trick.
  push @Data, [$k, $v];
}

# Populate the uniqified %Result hash. The push() adds the second 'aaa''s
# values after the first's.
for (@Data) {push @{$Result{$_->[0]}}, (split /,/, $_->[1])};

# Loop & Print; or whatever...
for (sort keys %Result) {print $_, " ", join ',', @{$Result{$key}}, "\n"};


### Here are the datastructures ###

# The uniqified %Result looks like this.
%Result = (aaa => [], bbb => [], ccc => []);

# The intermediary @Data looks like this:
@Data = (
         ['aaa',   '438287,3231'], ['bbb', '539634,4342'], ['ccc', '558180,43555'],
         ['aaa', '10878,8678666'], ['bbb',   '9274,6546'], ['ccc',    '23386,393'],
         );

# The final datastructure actually looks like this:
%Result = (
           aaa => [438287,  3231, 10878, 8678666],
           bbb => [539634,  4342,  9274,    6546],
           ccc => [558180, 43555, 23386,     393],
          );


__END__
aaa  438287,3231
bbb  539634,4342
ccc  558180,43555
aaa  10878,8678666
bbb  9274,6546
ccc  23386,393


-- 
As a cat owner, I know this for a fact...
Nothing says "I love you" like a decapitated gopher on your front porch.

# ===== Want to unsubscribe from this list?
# ===== Send mail with body "unsubscribe" to macperl-request@macperl.org