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


In reply to Re: Send hash of hash arguments to sub by kcott
in thread Send hash of hash arguments to sub by Dr Manhattan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.