Cody Pendant has asked for the wisdom of the Perl Monks concerning the following question:
I'm getting some data out of SQL (fetchrow_hashref) in the form:
{season => 1, ep => 1, title => 'Hellmouth' }, {season => 1, ep => 2, title => 'Harvest' }, {season => 1, ep => 3, title => 'Witch' }, {season => 1, ep => 4, title => 'Teacher' }, {season => 1, ep => 5, title => 'First Date'}, # [etc] {season => 2, ep => 13, title => 'Bad' }, {season => 2, ep => 14, title => 'Assembly' }, {season => 2, ep => 15, title => 'School' }
That is, it's a long list of episodes, some in season n, some in season n+1 and so on. I need to put it into a structure like this:
$appearances = [ {season => 1, eps => [ {title => 'Hellmouth' }, {title => 'Harvest' }, {title => 'Witch' }, {title => 'Teacher' }, {title => 'First Date'} ] }, {season => 2, eps => [ {title => 'Bad' }, {title => 'Assembly' }, {title => 'School' }, ] } ]
An array of hashes for each season, and each episode an entry in an array within that hash.
Here's how I did it late last night, and it works, but there must be a better way than this:
my $temp_hash = {}; my $last_season = 0; my $appearances = []; while ( my $ref = $sth->fetchrow_hashref() ) { if ( $ref->{season} != $last_season ) { # if the season has changed, unless unless ( $last_season == 0 ) { # unless it's the first season we encounter push( @{$appearances}, $temp_hash ); # put the data for that season into # the data structure $temp_hash = {}; # make the hash empty again } } $temp_hash->{'season'} = $ref->{'season'}; push( @{ $temp_hash->{'eps'} }, { title => $ref->{'title'} } ); $last_season = $ref->{season}; # put the season into the marker variable } push( @{$appearances}, $temp_hash ); # need to put what's left over into the data # structure after the while() finishes.
Where I build little structures and append them onto the big structure by watching for a change of season, with extra clauses for the first time around and so on.
I await your advice. Please be kind.
Update: Forgot to say, yes the data comes out in the right order, that's not part of the problem, and no, it's not an HoAoH, is it? It's an AoHoWhatever.
($_='kkvvttuubbooppuuiiffssqqffssmmiibbddllffss')
=~y~b-v~a-z~s; print
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: building an HoAoH ... very badly
by Errto (Vicar) on Jan 10, 2005 at 03:53 UTC | |
|
Re: building an HoAoH ... very badly
by Thilosophy (Curate) on Jan 10, 2005 at 04:04 UTC | |
|
Re: building an HoAoH ... very badly
by broquaint (Abbot) on Jan 10, 2005 at 05:09 UTC | |
|
Re: building an HoAoH ... very badly
by Ovid (Cardinal) on Jan 10, 2005 at 04:08 UTC | |
|
Re: building an HoAoH ... very badly
by Thilosophy (Curate) on Jan 10, 2005 at 05:04 UTC |