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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.