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

Re: [MacPerl] Merging elements




Pete Prodoehl wrote:
>I'm a bit stuck, and would appreciate any help. 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...

below is a script which does what you want, I've commented it, run it first
to get an idea of how it's doing what it does.

#! perl -w

#=========== declare includes =============

use strict;
use diagnostics-verbose;

#========== declare variables =============

my(@raw_data,%processed_data,%final);
my($in,$out,$key);

#============= script body ================
$in=<DATA>;
$in=~tr/ //s; #take out any unwanted extra spaces
@raw_data = split(/\s/,$in); #load the data into an array for manipulation

# because the values are unique and the keys
# aren't, it's better if we build a hash
# using the unique info as the key (less brain strain)

while (@raw_data) {
    #the first array element will be a letter combo (aaa, bbb, ....)
    $out = shift(@raw_data); #let's pull it out so we can use it
    #the next array element will be a number (111,222 ...)
    $processed_data{$raw_data[0]}= $out; #making hash key value pair
    shift(@raw_data);#killing the now unwanted array element
}


print "the data has been loaded into a hash using the unique elements as
keys:\n";
for $key(keys(%processed_data)) {
    print " \$key:$key  value:$processed_data{$key}\n";
}


# so now we have a hash containing the info we want to process
# let's re-order the info, swapping the keys and the values the way we
# really want them

for $key(keys(%processed_data)) {
    if ($final{$processed_data{$key}}) {
	#if the hash entry already exists
	#we only have to append to the hash value
	$out = $final{$processed_data{$key}};
	$final{$processed_data{$key}} = "$out,$key";
     }else{
	 #if we arrive here we make a new hash entry
	 #swapping the keys and the values from the
	 #first hash we made
	 $final{$processed_data{$key}}=$key;
     }
 }


 print "\n now the keys and values have been swapped:\n";

 for $key(keys(%final)) {
      print " \$key:$key  value:$final{$key}\n";
 }


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

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