开发者

How do you access information in a hash reference that has been passed to a sub-routine?

I am trying to use hash references to pass information to sub-routines. Psuedo code:

sub output_detail {
    Here I want to be able to ac开发者_Python百科cess each record by the key name (ex. "first", "second", etc)
}

sub output_records {
    I want to use a foreach to pass each record has reference to another sub-routine
    that handles each record.

    foreach $key ( sort( keys %someting) ) {
        output_detail(something);
    }
}

%records = ();

while ($recnum, $first, $second, $third) = db_read($handle)) {
    my %rec = ("first"=>$first, "second"=>$second, "third=>$third);
    my $id = $recnum;
    $records{$id} = \%rec;
}

output_records(\%records);

I'm not sure how to de-reference the hashes when passed to a sub-routine. Any ideas would be very helpful.

Thanks


Use -> to access keys of a hash ref. So, your argument to output_records will come through as a scalar hash ref.

sub output_records {
    my $records = shift;
    my $first = $records->{"first"};
}

See perlreftut for more info.


sub output_detail {
    my $hash = shift;
    my $value = $$hash{some_key};
}

sub output_records {
    my $hash = shift;

    foreach my $key (sort keys %$hash) {
        output_detail($hash, $key);  
        # or just pass `$$hash{$key}` if you only need the value
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜