This is a query about best practice in approaching this problem. The code below illustrates the problem, and the solution I have used (pre-defining a hashref).
use strict; my $href; fill_hashref ($href); print qq|TEST 1: $_\t$href->{$_}| for keys %$href; # Prints NOTHING my $empty_hash_href={}; fill_hashref ($empty_hash_href); print qq|TEST 2: $_\t$empty_hash_href->{$_}\n| for keys %$empty_hash_h +ref; # Works as expected sub fill_hashref{ my ($lref) = @_; $lref->{RETURNVALUE}="I would like to see this"; }
I'm guessing there is some coding design pattern with a best practice that wiser monks recognize here, and enlighten me : WWLD ? ( What would Larry do ?)

Update: Just to clarify - what I'm struggling with is that I occasionally forget to initialize the href passed in, and get bad results.

I am aware that an alternate solution is to use something like this in the sub:

$_[0]->{WHATEVER}="blah";
But that has a certain ugliness (smell ?) to it, and was looking for a prettier, more aromatic solution.

While I am at it - how would this look/behave in perl6 ?

     Syntactic sugar causes cancer of the semicolon.        --Alan Perlis


In reply to Populating an undefined hashref in a sub by NetWallah

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.