开发者

Iterating over A Perl Hash is printing out a memory address

The following subroutine is used to iterate over an array of Nodes (each with a continent in its hash) and return a list of all the countries:

sub getContinentsServed{
    my $self = shift;
    my $temp = $self->{cityListRef};
    my %hash = {};
    my $h_ref = \%hash;
    foreach my $cont (@{$temp}){
        $h_ref->{$cont->{continent}} = '1';
    }
    print "Continents Served: ";
    foreach my $coord (keys %hash){
        print $coord;
        print " , ";
    }
} 

I'm fairly certain that this contains all the correct data, but when I try to print the values I get this as my result:

Continents Served: Australia Europe North America South America Asia Africa HASH(0x100949a70) 

Does anyone know why I would get that final element HASH(0x1009...). I'd rather this not appear, but all I'm doing is开发者_如何学Python iterating over keys, so I'm not sure why or how that would be there.


my %hash = {};

Is bad and wrong. This is setting %hash to contain an entry where the key is the stringified value of {} (a hash-reference, so as a string it will be HASH(0xblahblah)) and the value is undef.

All you actually needed to write was my %hash; (or my %hash = (); but that's already implied, so it's not necessary to write it). Or you could do my $h_ref; and never use %hash at all (initializing to {} is still unnecessary because of autovivification).

If you had use warnings turned on, you would at least have gotten an "odd number of elements in hash" or "reference found where even size list expected" (depending on the age of your perl) warning on that line to give you a hint that something is wrong there.


The last $cont->{continent} has a hash reference as its value.

Removing unnecessary redirection and improper hash usage:

use List::MoreUtils 'uniq';

sub getContinentsServed {  # get_continents_served is more preferred
    my $self = shift;

    print
      'Continents Served: ',
      join ', ', map { $_->{'continent'} } uniq @{ $self->{'cityListRef'} };

    return;
}


@{$temp} where $temp = $self->{cityListRef} almost certaintly has a hash as its last member.

Update: I'm wrong, and Alan Haggai Alavi is correct. It's the ->{continent} on this last member that is the hash.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜