in reply to trouble with packages/eval/variable-scoping

$gold is not explicitly used in loadP() but in saveP().

Hence it's not in the closure of loadP and the dynamic eval can't find it.

That's how Perl decides to populate the so called variable (Scratch)Pad of a sub at compile time. ¹

Workarounds

Cheers Rolf
(addicted to the Perl Programming Language :)
see Wikisyntax for the Monastery

Updates

¹) see also PadWalker

²) see Re^2: trouble with packages/eval/variable-scoping (caller's scope)

  • Comment on Re: trouble with packages/eval/variable-scoping

Replies are listed 'Best First'.
Re^2: trouble with packages/eval/variable-scoping
by Ratazong (Monsignor) on Aug 29, 2024 at 12:19 UTC

    Thanks a lot, LanX!

    So I changed the sub loadP to the following, and it works :-)

    Rata (having learned something today)

    
    sub loadP
    {
    	$gold = 0;                                              # <--- new
    	my $savefile = new FileHandle("xxx.ptysav", "r");
    	my $lines  = join("",($savefile->getlines()));
    	my $result = eval $lines;
    	close ($savefile);	
    }
    

      IIRC, this also works:

      $gold if 0;

      It doesn't modify the var. It doesn't result in any run-time code at all.

      Demo:

      $ perl -Mv5.10 -we \ 'do { my $x = 42; sub { say eval q{$x} } }->()' Variable "$x" is not available at (eval 1) line 1. Use of uninitialized value in say at -e line 1. $ perl -Mv5.10 -we \ 'do { my $x = 42; sub { $x if 0; say eval q{$x} } }->()' 42

      Update: Tested and added demo.

        That's kinda cool if it works (can't test ATM)

        But this relies on constant folding happening after the PAD was populated.

        I'd feel uncomfortable to use an undocumented feature and risk to run into problems in later perl versions.

        IIRC they started to deprecate the similar my $var if 0; (poor man's state ) so I'm kind of sceptical that's guaranteed to stay.

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        see Wikisyntax for the Monastery