in reply to Re: Code Efficiency
in thread Code Efficiency

Declare variables as late as possible (if you want the advantages of use strict;). -- Huh? While declaring variables in an as restrictive scope as necessary is usually a good thing, what does that have to do with any advantage of use strict?

The first use of a variable is usually important for consequent uses. If you declare the variable as late as possible, you make sure the program breaks when you remove the first use, but not all others.

my $foo; # Predeclared: bad style # Usually done by C-coders, who predeclare a whole bunch of variables: # my ($foo, $bar, $baz, $quux, $whatever, $i, $think, $is, $needed, $a +nywhere); ... $foo = foo(); ... print $foo;
Now, I remove the assignment:
my $foo; ... print $foo; # No error, just a warning at run time.
However, if you declare $foo as late as possible:
my $foo = foo(); # Declared when needed ... print $foo;
Removing the assignment again:
... print $foo; # Error at compile time!

Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }

Replies are listed 'Best First'.
Re: Code Efficiency
by Abigail-II (Bishop) on Mar 25, 2004 at 13:27 UTC
    Yes, but what does that have to do with my question?

    Abigail

      what does that have to do with any advantage of use strict?

      The advantage of strict is detecting mistakes at compile time. If you predeclare (not declare as late as possible), you lose that benefit in one very common situation: removing the first use.

      To fully take advantage of strict, you should delay declaration until it is *necessary*.

      Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }