in reply to Data structure transformation
(Subquestion: is that constuct I used in the foreach() what's called a Schwartian transform?)#!/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;
Update:
(Subanswer: It isn't)
Clearly I'm insufficiently awake. %collate can be built like this:
The transform is redundant.foreach (@input) { push(@{$collate{$_->{department}}}, $_); }
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:
|
|---|