I am trying to write a generic 'set' method. A simplified fragment:
my %drink; # other attribute hashes sub set { my ($key, $attr, $value) = @_; my $hashref; eval "\$hashref = \\\%$attr"; if ( !defined $hashref ) { carp 'Invalid attribute name'; } else { $hashref->{$key} = $value; } }
The call to this subroutine:
set('larry', 'drink', 'Old Speckled Hen');
This does not work, i.e. it does not actually alter the 'real' hash (%drink). I have discover two fixes, but I cannot explain why either works 1. If I stringify the actual hash (%drink). After the assignment, if I add:
print "$drink{$key}\n";
it works. It seems to 'commit' $hashref. Using Data::Dumper or Devel::Peek::Dump also fixes it. 2. If I make the hash an 'our' variable it works. I'm setting warnings and use strict. Tried on 5.8.6 on Fedora and 5.8.7 on Windows. What is going on?

In reply to eval a reference to a my hash by cdarke

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.