Jonathan Batchelor writes:

> I have a data structure similar to the following:
> 
> @hosts = ( list of hashes like below ... );
> %hosts = ( name => "hostname",
>            ipaddr => "www.xxx.yyy.zzz",
>            location => "location"
>          );
> 
> How can produce a sorted list of the hashes based on the hostname and then
> access each hash to print the details.
> 
> Or is there a better way of organising my data?

There might be better way.  It's not clear to me that you need the
array of hashes at all.  If you don't, try the following.

Create a hash of hashes:
       %hosts = ( hostname1 => {ipaddr => "www.xxx.yyy.zzz",
                                location => "location"},
                  hostname2 => {ipaddr => "www.xxx.yyy.zzz",
                                location => "location"},
                  .....
                );

To get a sorted list of hostnames, do:
       @hostnames = sort keys %hosts;

Now you can either use the alphabetically sorted hostnames array, or
quickly look up a particular hostname with the hosts hash.  If you do
the latter often, the hash will be more efficient than looking through
the array.  For example, if you want to allow a user to enter a
hostname and look up its address, using the hash will probably be
faster and easier.  If you only ever want to access the data sorted by
hostname, however, there's no reason not to use an array of hashes.

To print out the data you can do something like:
        foreach my $hostname (@hostnames) {
            print "Hostname: $hostname\n";
            print "Address:  ".$hosts{$hostname}->{ipaddr}."\n";
            print "Location: ".$hosts{$hostname}->{location}."\n";
        }

+ Richard J. Barbalace

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to