The reason your subroutines are not defined in your package 'MyPackage' is that your subroutines are being defined in package main, rather than in package MyPackage. Even though you use a reference to the subroutine main_package_vars that is defined in package MyPackage (i.e. package_vars3) the subroutine (main_package_vars) still runs in the context of package main and the subroutines it defines are defined in package main.

By using fully qualified names, you can create the subroutines in any package name space. One option is to use __PACKAGE__ to pass the name of your package to main_package_vars and use this to create fully qualified names.

You might also be interested to use Data::Dumper to inspect the namespace of your package.

Here is a modified version of one of your code samples that might help you understand what is happening:

#!/usr/bin/perl -w use strict; use feature ':5.10'; BEGIN { sub package_vars { my $package = shift; foreach(@_) { eval "sub ${package}::$_ { my \$p = shift; \$p->{$_} = \$_[0] if \@_; \$p->{$_}; }" } } } package MyPackage; use Data::Dumper; { main::package_vars( __PACKAGE__, qw(one two three) ); print Dumper(\%MyPackage::); sub new { my $package=shift; my $parms=$_[0]; my $this={}; foreach(%$parms) { $this->{$_}=$parms->{$_}; } bless $this, $package; } } package main; my $p=new MyPackage({three => 3,}); $p->two(1); printf "two=%d, three=%d\n",$p->two, $p->three;

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