[EMAIL PROTECTED] wrote:
> Hi,
>
> I am doing some studies on sub modules and Lexical variables (my).
>
> With regards to diagram 1 below, what can I do so that the lexical $counter
> can count up to 4.
>
> Of course, one way of doing this is to change the lexical $counter into a
> global variable as seen in diagram 2 but I dont think this is a good idea as
> the sub-module will then have a mixture of both lexical (my) and global
> variables.
>
> So, are there any other ways of writing in diagram 1 so that the $counter can
> count up to 4?
> Thanks
>
>
>
> ############## Diagram 1 ---- lexical $counter t###############
> use strict;
> my $anything = 0;
>
> while ($anything < 5){
> $anything +=1;
> &testing_module ;
> }
>
>
> sub testing_module {
> my $counter = ();
> if ($counter < 5){
> $counter += 1;
> }
> }
>
> ###########################################
> ############# Diagram 2 -------- global $counter below
> ######################
> use strict;
> my $anything = 0;
> my $counter = (); #global counter
>
> while ($anything < 5){
> $anything +=1;
> &testing_module ;
> }
>
>
> sub testing_module {
> $counter = ();
> if ($counter < 5){
> $counter += 1;
> }
> }
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++;
}
}
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:
{
my $counter;
sub testing_module {
$counter = 0 unless defined $counter;
if ($counter < 5) {
$counter++;
}
}
}
HTH,
Rob
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/