Dear monks,
I am experimenting with perl modules, and am stuck: I have the package p2 (see below), and am calling the subs saveP and loadP from my main script. When loading and evaluating the data, I get the error message
Variable "$gold" is not available at (eval 15) line 1, <GEN7> line 1.I am confused: why is $gold visible in saveP (when I write it), but not in the eval?
And how can/should I resolve this?
Please enlighten me! Rata
In my main Tkx-script - called from a menu:
sub saveP{ p2::saveP(); }
sub loadP{ p2::loadP(); }
My package p2:
package p2;
use strict;
use warnings;
use Data::Dumper;
use FileHandle;
my $gold = 5000;
1;
#====================================================================================================
sub saveP
{
my $savefile = new FileHandle("xxx.ptysav", "w");
$savefile->print("\$gold = $gold;\n");
close ($savefile);
}
#====================================================================================================
# note: eval on files (or strings) is dangerous - see the reply of afoken below
# https://www.perlmonks.org/?node_id=11161417
sub loadP
{
my $savefile = new FileHandle("xxx.ptysav", "r");
my $lines = join("",($savefile->getlines()));
my $result = eval $lines; # <- here is the eval
close ($savefile);
}
The save-file is as expected: $gold = 5000;
In reply to trouble with packages/eval/variable-scoping by Ratazong
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |