Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re: Data structure transformation

by araqnid (Beadle)
on Apr 07, 2001 at 20:29 UTC ( #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?)


(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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://70725]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2017-05-26 07:57 GMT
Find Nodes?
    Voting Booth?