in reply to creating a variable in an if statement

Serveral people have already pointed out why the solution in your last snippet (the my before your if statement) is the best. You should just accept this rather than try for that "more perfect" one liner.

I just wanted to quickly address the confusion about the error message regarding masking the variable. You might think that there will never be a second my declaration for the same variable (thus masking the first declaration) because only one side or the other of the || will be true. If the first condition is true then you're fine; only one declaration is executed. But what does the parser actually do when the first condition is false?

The first my declaration happens, the some_code() assignment happens and only then is it found to be false. Now the parser moves on to the other side of the || and hits a second my declaration. It doesn't somehow forget or throw away what happened before the || just because it didn't turn out to be true.

Replies are listed 'Best First'.
Re^2: creating a variable in an if statement
by starbolin (Hermit) on Jan 24, 2008 at 08:34 UTC

    Actually, perl has a three pass 'compiler', for want of a better term, followed by a tree-threaded interpreter. The order of execution is not known at the time the declarations are compiled into the code tree. If you have multiple declaration with a statement there is no 'execution order' all the declarations get compiled into the code tree initially.

    perlguts says 'bottom up' I'm not sure what this means. I think in this case it means that the 'if' is built from the inside out and the compiler, upon building out one branch of the conditional, can't see down the other branch to spot the other declaration, but that's just speculation on my part.


    s//----->\t/;$~="JAPH";s//\r<$~~/;{s|~$~-|-~$~|||s |-$~~|$~~-|||s,<$~~,<~$~,,s,~$~>,$~~>,, $|=1,select$,,$,,$,,1e-1;print;redo}