my $myscale = $scale // 1;
The problem is that $scale may be not defined because it is not declared. The code above causes a compile time error.
The following code incorporates many of replies you have already received. Note that the same code must work in three situations. It is tempting to write the code as a function and call it wherever it is needed. This does not always work correctly because it would be testing declare and define in the scope of the function, not of the call.
use strict; use warnings; use Test::Simple tests => 3; { # $scale is not declared my $myscale = do{ use strict 'vars'; no warnings 'uninitialized'; (do{eval '$scale'; $@} ) ? 1 : (eval '$scale') // 1; }; ok( $myscale == 1, 'not declared'); } my $scale; { # $scale declared, but not defined my $myscale = do{ use strict 'vars'; no warnings 'uninitialized'; (do{eval '$scale'; $@} ) ? 1 : (eval '$scale') // 1; }; ok( $myscale == 1, 'declared, but not defined'); } $scale = 7; { # $scale declared, and defined my $myscale = do{ use strict 'vars'; no warnings 'uninitialized'; (do{eval '$scale'; $@} ) ? 1 : (eval '$scale') // 1; }; ok( $myscale == $scale, 'defined'); }
The logic is confusing. The first eval compiles the string '$scale' recognizing it as a variable. If it is not declared, this is an error under 'no strict vars'. That error is signaled with the system variable $@. Because $@ is the last value in the do-block, it is returned. We only care about its logical value. "True" means that there was an error and the variable is not declared. We return the default value (1). "False" means there was no error, the variable is declared. At this point we would like to do the normal assignment, but our code has to compile in all three cases. We call eval again. We know that there will not be an error. This time, we want the return value (the value of the variable). If that value is undef, we use the default value. The result of all this logic is returned by the outer do and assigned to $myscale.
In reply to Re: detecting an undefined variable
by BillKSmith
in thread detecting an undefined variable
by LloydRice
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |