On Thu, 22 Sep 2005, Dave Adams wrote:

> I have a hash that I need to use later and display some values in a
> particular order.  Perl comes up with its own way of ordering it but I
> am wondering if I can instruct perl to have it listed in the way that
> I want.
> 
> Here is the code
> 
> 
> #!/usr/bin/perl -w
> use strict;
> 
> my $page = {
>     AUTHOR=>"John Smith",
>     LANGUAGE=>"English",
>     TITLE=>"Treasure Island"};
> 
> print ref($page). "\n";
> print $page->{AUTHOR} . "\n";
> 
> print keys %{$page};
> print "\n";
> print sort (keys %{$page});

I would add another level to my hash. Something like this

my $page = {
  AUTHOR => {
        val => "John Smith",
        order => 1,
  }
  LANGUAGE => {
        val => "English",
        order => 2,
  TITLE => {
        val => "Treasure Island",
        order => 3,
};        

then you can just walk over the hash using your custom sort key to get in 
the order you want.

foreach my $f (sort { $page->{$a}->{'order'} <=>  $page->{$b}->{'order'} 
keys %$page ) {

## You can print whatever you want here ...
        
print qq{
key: [$f],  val: [$page->{$f}->{'val'}], order: $page->{$f}->{'order'} 
};

}

hope that helps,
waldemar


-- 
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