in reply to Re: sorting hash by value when value is an array ref
in thread sorting hash by value when value is an array ref

foreach $homework (@homeworks) { $query = "SELECT PointValue,DueDate FROM Homework WHERE ClassID = +\'$courseID\' AND SectionID = \'$sectionID\' AND InstructorID = $ins +tructorID AND HomeworkName = \'$homework\'"; $statementHandle = $databaseHandle -> prepare($query); $statementHandle -> execute(); while(@rowArray = $statementHandle -> fetchrow_array()) { $homeworkHash{$homework} = [$rowArray[0],$rowArray[1]] +; } } # now the sorting my @sorted = sort { $homeworkHash{$a}[1] cmp $homeworkHash{$b}[1] } ke +ys %homeworkHash; # I then pass the @sorted to a template under the name homeworks and i +n the template I use this to print out the hash. [% FOREACH key IN homeworks %] <th valign="bottom" class="Homework"><span id="points">[% key +%]</span><br>[% homework.$key.0 %]<br>[% homework.$key.1 %]</th> [% END %]
This doesn't print out a thing in the template. It is as if the @sorted in empty.

Replies are listed 'Best First'.
Re^3: sorting hash by value when value is an array ref
by jdporter (Paladin) on Nov 16, 2004 at 03:06 UTC
    Well, I don't know what all that non-Perl junk is... but I'm inclined to guess that [% FOREACH key IN homeworks %] is iterating over the keys in some other order, and that you're throwing away the result of the sort you so carefully set up. Do you know a way to set the key for iteration based on the contents of @sorted ?
      I pass the @sorted to the template( it is perl, it's the Template-Toolkit). I pass it like this.
      my $vars = { homework => \%homeworkHash, homeworks => \@sorted, }; my $tt = Template->new({ INCLUDE_PATH => "/inetpub/wwwroot/lib", WRAPPER => 'wrapperInstructor.htm', }); $tt->process('ClassGrades.htm', $vars)||die $tt->error();
      The Template then uses the array named homeworks which is identical to @sorted in the perl script. The [% FOREACH key IN homeworks %] just iterates through the array and prints inserts each element into the hash to get the value.
        If I pass a list of the keys to the template, everything prints out fine. So I'm assuming there must be a problem in my perl script.