in reply to detecting an undefined variable

I completely agree with the remarks of haukex, LanX and Athanasius regarding hashes, but if you just gotta do something like this, here's another way:

c:\@Work\Perl\monks>perl -le "use 5.010; ;; use strict; use warnings; ;; sub extscale (); ;; my $myscale = extscale // 1; print $myscale; ;; sub extscale () { no strict 'vars'; no warnings 'once'; return $scale; } " 1
This is entirely a compile-time solution. Note that the  extscale function must be either declared (as above) or defined before it is used. Note also the use of a prototype to achieve the desired effect.


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

Replies are listed 'Best First'.
Re^2: detecting an undefined variable
by LanX (Saint) on Sep 21, 2019 at 15:25 UTC
    Nice!

    Here a generic - albeit slower - solution for definedness

    use strict; use warnings; use Data::Dump qw/pp dd/; #my $scale =42; #our $scale =42; sub var { eval $_[0];# or die $@; } my $myscale = var('$scale') // 1; pp $myscale;

    and inspecting the errorstring in $@ can help checking for existence instead.

    Global symbol "$scale" requires explicit package name (did you forget to declare "my $scale"?) at (eval 1) line 1.

    update
    of course using eval directly is shorter

    use strict; use warnings; #my $scale =42; #our $scale =42; my $myscale = eval('$scale') // 1; print $myscale;

    but I prefer encapsulating such magic to be able to capture side effects like polluting $@ or potential injections by tainted input.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice