in reply to package variable does not persist

As a start on an SSCCE, I wonder if something like this might be happening:

# Module.pm package Module; use warnings; use strict; use vars qw($configvar); sub what_is_configvar { if ($Module::configvar) { return 'true'; } else { return 'false'; } } sub menu { print 'in menu(): ', what_is_configvar(); } sub inModule { print 'in Module: ', what_is_configvar(); } inModule(); 1;
And then:
c:\@Work\Perl\monks\Anonymous Monk\1221498>perl -le "use warnings; use strict; ;; use Module; ;; $Module::configvar = 1; ;; Module::menu(); " in Module: false in menu(): true


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^2: package variable does not persist
by haukex (Archbishop) on Sep 01, 2018 at 10:24 UTC

    This is a good guess, and I think it's noteworthy that this happens even if the variable appears to be being set before use Module:

    $ perl -I. -wMstrict -le '$Module::configvar=1; use Module; Module::menu();' in Module: false in menu(): true

    Because use gets run in an implicit BEGIN block, so the code in Module.pm will always be executed before the code that sets $Module::configvar=1;. One solution is to say BEGIN { $Module::configvar=1; } before use Module;.

Re^2: package variable does not persist
by Anonymous Monk on Sep 01, 2018 at 18:35 UTC
    Thank you all for asking the right questions about my somewhat wrongly sought wisdom, sorry about that. AnomalousMonk answered Corion's question for me and this good advice was being followed too: "Just the exercise of preparing the SSCCE may reveal to you the root cause of the problem." and it worked of course. I now understand the problem so the solution is obvious. I knew it was some dumb mistake.

    One thing the use Module line does is check for params and dispatches subs based on them which eventually terminate the process.

    If there are no params the use Module line does no dispatch and the script proceeds to set the package var and call a sub that sees it and all is well.

    If there are params then nothing in the script happens after the use Module line, like setting the package variable, and that was the confusing part.

    Since the use line is indeed hijacking my flow as AnomalousMonk noticed, haukex suggested setting the var in a BEGIN block, and now that I understand the problem it all makes sense and works as expected. Thank you monks!