in reply to conditional definition of variables

"my" declares a variable. A variable should not be declared more than once in a block. Simply leave out the (second) "my":

$var = "zzz\n" unless defined $var;

However, if you want to print the variable, you should make sure that $var is defined (otherwise you get a warning with "use warnings;"):

$var = defined($var) ? "zzz\n" : "";

By the way, including another script with "do" isn't good practice. Consider making it a module (perlmod).

Replies are listed 'Best First'.
Re^2: conditional definition of variables
by stephanm (Sexton) on Aug 23, 2008 at 14:12 UTC
    Thanks, betterworld.
    Your proposal works.
    When you say a variable should not be defined more than once in a block - I did not think I did that in the code as the second declaration is conditional to the variable not being defined.
    Am I missing anything here?
      "Definition" (or declaration) of the variable happens at compile time. The conditional happens at run time.

      So, if you have

      my $var = "..." if EXPR;
      you will have all the compile time effects, and maybe the runtime effects. This was abused (with 'EXPR' being 0) to get "state" variables in 5.8 and before (which didn't always 'work'), which in turn let to the "state" keyword in 5.10.