http://www.perlmonks.org?node_id=70725


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: