BEGIN { sub main_package_vars { foreach(@_) { eval "sub $_ { my \$p = shift; \$p->{$_} = \$_[0] if \@_; \$p->{$_}; }" } } }

Why do you put this in a BEGIN block? It serves no purpose, at least when Perl looks at it.

Also, why are you using string-eval, when the plain eval works just as well. Also see Class::Accessor.

sub main_package_vars { foreach my $name (@_) { no strict 'refs'; *{ $name } = sub { my $p = shift; $p->{$name} = $_[0] if @_; $p->{$name}; }" } }

In this next snippet from MyPackage, I don't understand why you use string-eval, and also why you try to execute the same statement twice:

BEGIN { eval "*package_vars2 = \*main::main_package_vars"; *package_vars3 = \*main::main_package_vars; }

The subroutine package_vars3 does not exist:

package_vars3( qw(one two three) );

What problem are you trying to solve? Do you want to have a hash using which you get/set variables?

Maybe an object based on a plain hash using AUTOLOAD is already enough? If you want control over what keys get stored, again, see Class::Accessor.</c>


In reply to Re: Perl templating/macro creating using 'BEGIN'... by Corion
in thread Perl templating/macro creating using 'BEGIN'... 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.