Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Data Structure Transformation

by ELISHEVA (Prior)
on Jan 31, 2011 at 21:17 UTC ( [id://885364]=note: print w/replies, xml ) Need Help??


in reply to Data Structure Transformation

I imagine there is some module out there that does it, but writing a general purpose routine to convert an array of key-value pairs into a hash of arrays (HoA) is less than 10 lines of code:

use strict; use warnings; sub convertKeyValueArrayToHash { my ($aData, $sKeyName, $sValueName) = @_; my $hData={}; foreach (@$aData) { my $k = $_->{$sKeyName}; my $v = $_->{$sValueName}; push @{$hData->{$k}}, $v; } return $hData; }

And a working demo:

# ------------------------------ # Demo # ------------------------------ my $var = [ { 'city' => 'New York', 'name' => 'Bill' }, { 'city' => 'New York', 'name' => 'Ronald' }, { 'city' => 'Boston', 'name' => 'George' } ]; use Data::Dumper; my $hData = convertKeyValueArrayToHash($var,'city','name'); print Dumper($hData), "\n";

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://885364]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-26 08:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found