perl-diddler has asked for the wisdom of the Perl Monks concerning the following question:
Presumably, its because my 'our' definition is defining the variables in the 'enclosed scope' of the eval, so pop, come out of the eval, and the 'our' is no longer in effect and vars are undefined. I've tried moving the package and our out of the eval, but to save context, I was storing the package and trying to reset it when done -- but perl is giving a syntax error when I use a variable with a package. Seems odd, but I guess that's not allowed (though I don't see that documented under 'perlfunc package'). Here's code that demonstrates the problem:
Without "-w", it will give the correct answer, but with warnings -- which I'd also like to get rid of. I switched to trying to switch package because it didn't like a package declaration in an 'our' statement. Obviously this version of the code isn't removing the redundant package declaration from the sub.#!/usr/bin/perl -w use strict; use feature ':5.10'; # note use of BEGIN and 'caller' to achieve macro definition... BEGIN { sub class_vars { my $pck=caller; foreach(@_) { eval " my \$p=\"__PACKAGE__\"; package ${pck}; our \$$_; sub ${pck}::$_ { shift; \$$_ = \$_[0] if \@_; \$$_; } package \$p; " } } } package MyPackage; *class_vars=\&main::class_vars; { class_vars( qw(one two three) ); sub init_one_from_three { $one=$three-2; } sub new { my $package=shift; my $parms=$_[0]; my $this={}; foreach(keys %$parms) { $$_=$parms->{$_}; } bless $this, $package; } } package main; my $p=new MyPackage({three => 3,}); $p->two(1); $p->init_one_from_three; printf "two=%d, three=%d, one=%d\n",$p->two, $p->three, $p->one;
Any ideas from those more learned that I? Much appreciated!
|
|---|