简体   繁体   中英

How can I find the smallest value in a Perl hash of hashes of arrays?

I want to find the easiest way of finding the hash values

City {
  city1 -> Street1 -> [ high_street , 2]
           street2 -> [ low_street , 2]
  city2 -> Street1 -> [ high_street1 , 2]
           street2 -> [ low_street2 , 2]
  city3 -> Street1 -> [ high_street1 , 1]
           street2 -> [ low_street2 , 1]
}

This structure is sorted into a hash. How do I find the smallest value of the second elements of the arrays inside the second level of hashes?

I am expecting my smallest value to be - City3, street 1 - highstreet 1. This based on last value which is avilable at only one time. But 2 elements in the array has 1 times. But I just want to know first element first.

Is there any easy to find it?

my $City = {
    city1 => {
        Street1 => [ 'high_street', 2],
        street2 => [ 'low_street', 2],
    },
    city2 => {
        Street1 => [ 'high_street1', 2],
        street2 => [ 'low_street2', 2],
    },
    city3 => {
        Street1 => [ 'high_street1', 1],
        street2 => [ 'low_street2', 1],
    },
};

my $smallest_key1;
my $smallest_key2;
my $smallest_value;
foreach my $key1 (keys %{$City}) {
    foreach my $key2 (keys %{$City->{$key1}}) {
        if(not defined $smallest_value or $City->{$key1}{$key2}[1] < $smallest_value) {
             $smallest_key1 = $key1;
             $smallest_key2 = $key2;
             $smallest_value = $City->{$key1}{$key2}[1];
        }
    }
}
print 'Smallest: ', $smallest_key1, ', ', $smallest_key2, ', ', join(', ', @{$City->{$smallest_key1}{$smallest_key2}}), "\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM