I've been closing over hashes for years, for subs that need some persistent store, but not wanting to invoke memoize.

Below I've closed over a scalar and a hash. I get a warning of:

Use of uninitialized value $FIXED_STRING in hash element at ...

With hashes, this just works, but apparently the hash is empty, and that's fine. But the scalar value within the sub is undef.

What am I missing?

What is the easiest way to fix this, while still using a scalar to store a string, that is later used as a hash key?

#!/usr/bin/env perl # demo of closure around sub, with persistent string use strict; use warnings; for my $q ('a'..'g') { do_something($q); print "Done computing\n" } { my $FIXED_STRING = 'fixed_string'; my %persistent; sub do_something { my $x = $_[0]; $persistent{$x}{$FIXED_STRING} = rand; END { for my $k (keys %persistent) { print "$k: $persistent{$k}{$FIXED_STRING}\n"; } } } }

-QM
--
Quantum Mechanics: The dreams stuff is made of


In reply to Closure Over Scalar? by QM

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.