Jeff Smith wrote:
>
> Thanks for the feedback--maybe I screwed up but what happens for me is that
> the ordered array (1) only lists the keys, not the array values the hash key
> points to and (2) I still don't get an ordered list of the keys that are put
> in the "ordered" array--it comes out un-ordered.
>
> I took your line and just added a for loop/print for the ordered array and
> got "red,yellow,blue, orange, violet, green" only  as the result.
>
> I must be dense but using just a Keys expression can't return the values,
> can it??--wouldn't it be better to do a while/each and get both key and
> value for the HofA somehow??
>
> -----Original Message-----
> From: James Edward Gray II [mailto:[EMAIL PROTECTED]
> Sent: Wednesday, February 18, 2004 6:49 PM
> To: Smith Jeff D
> Cc: [EMAIL PROTECTED]
> Subject: Re: An Old Question on Sorting Hash of Arrays by Array element and
> th en by key
>
>
> On Feb 18, 2004, at 1:58 PM, Smith Jeff D wrote:
>
> > I am trying to sort a hash of arrays that is similar to the example
> > below.
> > I have a hash of arrays that I want to sort, first by the first
> > element of
> > the array, then by the key to the hash and don't care about other
> > elements
> > of the array (for sorting and without regard to case.
> >
> > %HofA = (orange=>['ZZZ', 'ANDY'],
> >    red=>['AAA', 'AL'],
> >    blue=>['mmm','Betty'],
> >    yellow=>['aaa', 'ZEUS'],
> >    green=>['DDD','Mary Joe']
> >    violet=>['MMM','Hugo']
> >    );
>
> my @ordered_keys = sort { $HofA{$a}[0] cmp $HofA{$b}[1]
>    ||
>    $a cmp $b } keys %HofA;
>
> I believe that will do it.  See if that gets you going.

Hi Jeff.

James was offering you a starting place. The only way to order
a hash is to order its keys, hence 'my @ordered_keys'. What you
do with this sorted list depends on what you want. For instance

  foreach (@ordered_keys) {
    printf "%s => %s\n", $_, $HofA{$_};
  }

Also, I wasn't sure whether, by

> (for sorting and without regard to case)

you meant that the string comparisons for the sort should be
case-insensitive. If so, then your sort should look like

  my @ordered_keys = sort {
    my ($aa, $bb) = lc $a, lc $b;
    $HofA{$aa}[0] cmp $HofA{$bb}[0] or $aa cmp $bb
  } keys %HofA;

HTH,

Rob



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to