{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' } #### $appearances = [ {season => 1, eps => [ {title => 'Hellmouth' }, {title => 'Harvest' }, {title => 'Witch' }, {title => 'Teacher' }, {title => 'First Date'} ] }, {season => 2, eps => [ {title => 'Bad' }, {title => 'Assembly' }, {title => 'School' }, ] } ] #### 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.