Brethern --

I want to sort a multidimensional hash by one of it's values and want to be able to build the sort criteria on the fly. I can get this to work fine if it isn't in a subroutine but as soon as I do this in a sub (passing the hash by reference), I start getting wacky results.

I am including the code I have been using to test and wondering what I am doing wrong.

Many thanks in advance,
mdog

$hash{'Me'}->{"name"} = "Me"; $hash{'Me'}->{"number"} = "7.7"; $hash{'Chuck'}->{"name"} = "Chuck"; $hash{'Chuck'}->{"number"} = "7.7"; $hash{'Zed'}->{"name"} = "Zed"; $hash{'Zed'}->{"number"} = "7.7"; $hash{'Wife'}->{"name"} = "Wife"; $hash{'Wife'}->{"number"} = "7.6"; $hash{'Dad'}->{"name"} = "Dad"; $hash{'Dad'}->{"number"} = "53"; $hash{'Michael'}->{"name"} = "Michael"; $hash{'Michael'}->{"number"} = "24"; test(\%hash); sub test{ my($hr) = @_; # sort criteria embedded: expected results @sortedKeys = sort { $hr->{$b}->{"number"} <=> $hr->{$a}->{"number +"} } keys %$hr; print "sort criteria embedded\n"; foreach my $sortedKey(@sortedKeys){ print $hr->{$sortedKey}->{"number"} . " " . $hr->{$sortedKey}- +>{'name'} . "\n"; } # sort criteria eval-ed: wacky results my $sortCriteria = '$hr->{$b}->{"number"} <=> $hr->{$a}->{"number" +}'; # WHAT AM I DOING WRONG ON THE NEXT LINE? @sortedKeys = sort { eval $sortCriteria } keys %$hr; print "\n\nsort criteria eval-ed\n"; foreach my $sortedKey(@sortedKeys){ print $hr->{$sortedKey}->{"number"} . " " . $hr->{$sortedKey}- +>{'name'} . "\n"; } }

The results:

sort criteria embedded 53 Dad 24 Michael 7.7 Me 7.7 Zed 7.7 Chuck 7.6 Wife sort criteria eval-ed 53 Dad 7.6 Wife 7.7 Me 7.7 Zed 24 Michael 7.7 Chuck

In reply to Sorting Hash: Sort Criteria Moved Into Eval by mdog

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.