Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Data structure transformation

by araqnid (Beadle)
on Apr 07, 2001 at 20:29 UTC ( [id://70725]=note: print w/replies, xml ) Need Help??


in reply to Data structure transformation

I can't eliminate the need for a temporary hash: having attempted it, I'm inclined to think it's not a nice thing to do, since you always seem to end up needing to collate as a side-effect of iterating over the input... Anyway, here's what I got:
#!/usr/bin/perl -w require 5.6.0; use strict; use Data::Dumper; our @input = ({ class => "Chemistry", department => "v6", count => 18 +}, { class => "German I", department => "v6", count => 27}, { class => "French II", department => "h4", count => 9 } +); our %collate; foreach (map { [ $_->{department}, $_ ] } @input) { push(@{$collate{$$_[0]}}, $$_[1]); } our @output = map { { department => $_, classes => $collate{$_} } } ke +ys %colla\ te; print Data::Dumper->new([\@output], [qw|*output|])->Dumpxs;
(Subquestion: is that constuct I used in the foreach() what's called a Schwartian transform?)

Update:

(Subanswer: It isn't)

Clearly I'm insufficiently awake. %collate can be built like this:

foreach (@input) { push(@{$collate{$_->{department}}}, $_); }
The transform is redundant.

Update II

tilly suggested I point out that the code doesn't work on older Perls, even 5.005.

Afaict, the changes for perl 5.005 would be:

  • replace "require 5.6.0" to the appropriate version
  • either change "our $foo" into "my $foo", or separate the declaration and assignments, and declare them in a "use vars qw($foo)" construct.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2024-04-25 07:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found