in reply to Send hash of hash arguments to sub

G'day Dr Manhattan,

You have a number of problems here.

When you call probability(), @_ contains all the keys and values from %hash, the hashref $hash{Mary}, and the value 0.8 from $hash{Mary}{Maria} (which is actually the value you want returned, so calling a subroutine is pointless in this instance).

When assigning those values to (%hash, $source, $target), they are all assigned to %hash leaving $source and $target undefined.

You're calling probability() with a leading ampersand (&). This probably isn't what you want and may (in the context of your real progam) be doing something unexpected. Don't add leading ampersands to your subroutine calls unless that's really what you want and you understand the implications of what you are doing! See perlsub for a more detailed discussion.

The code I suspect you want is probably closer to this:

$ perl -Mstrict -Mwarnings -e ' my %hash = (Mary => { Maria => 0.8}, other_keys => "other_values") +; sub probability { my ($hash_ref, $source, $target) = @_; return $hash_ref->{$source}{$target}; } my $test = probability(\%hash, "Mary", "Maria"); print "$test\n"; ' 0.8

-- Ken

Replies are listed 'Best First'.
Re^2: Send hash of hash arguments to sub
by tobyink (Canon) on Aug 14, 2013 at 08:58 UTC

    Another possibility is:

    my %hash = (Mary => { Maria => 0.8}, other_keys => "other_values"); sub probability (\%$$) { my ($hash_ref, $source, $target) = @_; return $hash_ref->{$source}{$target}; } my $test = probability(%hash, "Mary", "Maria"); print "$test\n";
    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name