Ralph Moritz said:
Sorry if this wasn't well explained. Say I'm getting the value of
$data by eval'ing a file, using the eval_file() sub defined below:
{ package Foo;
our $data;
sub eval_file {
my $file = shift;
open(my $fh, $file);
my $code = join('', <$fh>);
eval $code or die $@;
}
}
The built-in function do( $file) does what your eval_file( $file) does.
You can use that instead.
It seems I have to declare $data as a package variable (if I want to
use it as a class variable). Or is there a better way?
What do you call a class variable?
In my view, the code that deals with a class variable must be right
there in the class definition. A variable that is accessed from code
other than that (not to mention from code that is chosen at run time)
simply doesn't fit the term "class variable".
Perl isn't fascist about its OO model, you can use variables that don't
follow the rules if you have reasons to do so. Calling them class
variables is misleading.
That said, I believe you can do what you want with real class variables.
Untested:
{ package Foo;
{ # bare block to isolate $data
my $data;
sub data {
$data = shift if @_;
$data;
}
# other code that accesses $data directly
}
sub eval_file { do shift }
}
Now the code in whatever file you subject to ->eval_file would have to
set $data going through the accessor: Foo->data( $some_string). Likewise,
code that reads $data would have to use $x = Foo->data to do so. That's
what class variables are about.
If you can't or won't change the code that is eval_file()d, you can
isolate the package variable to eval_file (keeping everything else
as above):
sub eval_file {
our $data;
do shift;
Foo->data( $data);
}
The package variable $Foo::data is still accessible from everywhere,
but outside of eval_file its value is stored safely in a lexical
class variable, so it doesn't matter.
Anno