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:
(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:
- 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.
|
---|
In Section
Seekers of Perl Wisdom