in reply to [Solved] Parameter injection for testing

If you want to keep my $param private in file scope - instead of switching to our - then you need a setter function in that scope closing over $param

sub set_param { $param = shift }

A generic solution for various vars could be done with PadWalker or evals.

But I'd rather not see that compiled into production code.

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

Replies are listed 'Best First'.
Re^2: Parameter injection for testing
by LanX (Saint) on Aug 24, 2022 at 20:18 UTC
    > A generic solution for various vars could be done with PadWalker or evals.

    here a little demo using eval

    NB: the allowed vars must be bound inside the setter sub, otherwise the eval will fail.

    use v5.12; use warnings; { package TEST; my $param = 666; sub getset { my %args = @_; return [$param] # list of allowed vars unless @_; while ( my ( $var, $val ) = each %args ) { eval "$var = $val"; } } sub show { say $param; } } package main; TEST::show(); TEST::getset( '$param' => 42 ); TEST::show();

    666 42

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