good chemistry is complicated, and a little bit messy -LW |
|
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
Sorry, you just lost me -- you used a magic spell above my level. ;-)
In my previous example: #!/usr/bin/perl -w #use strict; use feature ':5.10'; BEGIN { sub instance_vars { my $pck=caller; foreach(@_) { eval "sub ${pck}::$_ { my \$p = shift; \$p->{$_} = \$_[0] if \@_; \$p->{$_}; }" } } } package MyPackage; *instance_vars=\&main::package_vars; { instance_vars( 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(2); printf "two=%d, three=%d\n",$p->two, $p->three; </code> I didn't have any reference to use or import. To invoke the code, I called a sub 'instance_vars', that was in a begin block. The reason the package statements are / were in the way they are is that the macros definitions are at the top of the file in 'main'. The way you are doing it may be the only way to do it, but it isn't close to as simple as the case for the 'instance' vars. You say that the above isn't satisfactory for 'singletons'. Why not? Aren't they global variables to each package that are initialized only once on the initial passthrough when the package is first read, and then retain their value as global variables in each package (or accessible via package::var) from without the package? The part where you put the classname.pm in the INC var likely prevents future 'use' statements from actually trying to find the file, I'd guess, and the 'use' statement does the same as: "package::import( qw(one two three) )"? It's workable, but I don't understand why something simple like I used for instance variables doesn't work. If putting a BEGIN block around a sub definition is useless, then how does this 'instance' var code work? It puts a sub definition in a BEGIN block which is then called in the code below. Also, the class_vars code *works* (with strict turned off, with warnings -- i.e. the variables being set in 'MyPackage' retain their values -- they aren't local but are treated as package variables, so I don't see how you can the subs don't work I think you are showing me an alternate way of doing what I'm doing, but I don't think it's answering my question -- which may have no good answer, i.e. the way you are doing it may be the only way -- I don't know. The 'sub' in main gets declared as a global as all named subs are, so in a BEGIN block or not, I think it is having the desired effect. The problem is adding an 'our' statement that is taken as a declarator for the rest of the block that the caller is in (not just in within the eval -- which is works for, but is ended when the eval ends and goes out of scope. In reply to Re^2: More Macro work...out to export a definition to next-outer level?
by perl-diddler
|
|