Rob Dixon wrote:
The way I would write that is to lessen the scope of $counter by
declaring it immediately before the subroutine that uses it:
use strict;
use warnings;
my $anything = 0;
while ($anything < 5){
$anything +=1;
testing_module() ;
}
my $counter = 0;
sub testing_module {
if ($counter < 5) {
$counter++;
}
}
Even if the variable cannot be used in code above the declaration of it,
it's still file scoped.
Furthermore, since assignment happens at run time (unless within a BEGIN
block), testing_module() is called before $counter is initialized. As a
result, Perl outputs the warning "Use of uninitialized value $counter in
numeric lt (<)".
but if you're desperate to prevent anything getting at the variable
apart from that subroutine then put it into a block of its own with the
declaration. Unfortunately that way variables can't be set to an initial
value so the subroutine will have to handle the initial condition
explicitly:
Not necessarily. This code before the sub is another option:
my $counter;
BEGIN { $counter = 0 }
But this problem is not limited to the variant where you put it all into
a separate block (see above).
--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/