RedThree has asked for the wisdom of the Perl Monks concerning the following question:

Silly question - with Perl or mod_perl, if I 're-declare' a value (say, "my $test=1;" then later in the program use "my $test=2;" instead of just "$test=2"), is there anything wrong with this?
  • Comment on Multiple 'my's in one block of mod_perl code?

Replies are listed 'Best First'.
Re: Multiple 'my's in one block of mod_perl code?
by GrandFather (Saint) on Jul 13, 2009 at 00:30 UTC

    Yes. Consider:

    use warnings; use strict; my $foo = 1; printFoo (); my $foo = 2; printFoo (); sub printFoo { print "\$foo = $foo\n"; }

    Prints:

    "my" variable $foo masks earlier declaration in same scope at noname.p +l line 8. Use of uninitialized value in concatenation (.) or string at noname.pl + line 14. $foo = $foo = 2

    Why? Because printFoo sees the second $foo during the compile phase and uses it for each call. However, the second $foo is uninitialized until the assignment is executed in the execute phase, just after the first call to printFoo. Therefore the first call to printFoo uses the uninitialized contents of the second $foo. If that seems confusing, try tracking down the problem in a 1000 line script!

    Silly question - you do always use strictures (use strict; use warnings;) don't you?


    True laziness is hard work
      Yes, I do, but I wanted to make sure there was a problem with this, so I knew double-checking my code was worth it. 1000s of lines indeed. Thanks!
Re: Multiple 'my's in one block of mod_perl code?
by ysth (Canon) on Jul 13, 2009 at 00:29 UTC
    No, though you will get a warning for it if they are in the same scope, to help keep you from doing it by accident. The new declaration will "hide" the old one until the end of its scope:
    my $test = 1; my $test = 2; # warns { my $test = 3; print $test; # prints 3 } print $test; # prints 2