perl-diddler has asked for the wisdom of the Perl Monks concerning the following question:
When I define package variables one two and three, with 'package_vars', it works.#!/usr/bin/perl -w use strict; use feature ':5.10'; BEGIN { sub main_package_vars { foreach(@_) { eval "sub $_ { my \$p = shift; \$p->{$_} = \$_[0] if \@_; \$p->{$_}; }" } } } package MyPackage; BEGIN { eval "*package_vars2 = \*main::main_package_vars"; *package_vars3 = \*main::main_package_vars; } { BEGIN { sub package_vars { foreach(@_) { eval "sub $_ { my \$p = shift; \$p->{$_} = \$_[0] if \@_; \$p->{$_}; }" } } } package_vars3( qw(one two three) ); 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;
When I try to use a copy of package_vars from 'main', I can't figure out how to import the symbol into the package to make it work -- at execution time I get undefined 'two'.
So how do I get my sub created in main, imported into my package so that my "defined" statement, the package vars3( qw(one two three) ); works? I've tried a few variations besides the ones shown here. But can't see why the symbols aren't created during the 'BEGIN' run the same as the actual sub's are.
Anyone know why this isn't working or how to make it work? Thanks --- trying to understand how some packages work among other things...
|
|---|