I was setting up some packages that call each other in a program, and, of course, have the common need to define accessor routines. Rather than going about using some CPAN module like Package::Pkg, I thought it should be easy to do what I want for my limited needs in a few lines of code (ok, you can stop laughing now). So I ran into a few snags.

Why isn't this as simple to do as it looks like it should be?

sub Instance_Var ($) { my $package=__PACKAGE__; my $var=$_[0]; my $accessor="$package::$var"; -> eval " sub $accessor { my $t=shift; $t->{$var}=$_[0] if @_; $t->{$var}; }"; }
Instead of not doing what I want through some indirect method, perl refuses to even compile the program, saying:
Global symbol "$t" requires explicit package name at line indicated by '->'.

Hmmmm. At first and second (third?) glance, I'm not sure why and not sure how it should be structured, other than 'not that'. Rather than trying things at random until something works (or using the, above, mentioned CPAN module or another), I'd like to understand why this wouldn't work to do what I 'think' is clear from the example (I.e. creating a named accessor that accesses a variable in an assoc array passed in as argument, and optionally set's to the value of the argument it if an additional argument is passed to it).

Thanks!


In reply to How do I get to this 'simple' helper? by perl-diddler

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.