[EMAIL PROTECTED] wrote:
In a large program, I guess there may be many programmers involved and each of these programmers are responsible to write their own sub rountine as required. Henceforth it will be very confusing and problematic if the programmers have to use variables from outside of their own sub-rountine.

No. A few variables outside the scope of various subs is a very natural thing, and the pure existence of such variables is neither confusing nor problematic.

However, just like a counter, there are times when we need to keep the values of these variables so that in the next iteration such as in while function, I can add one to the counter whose values was not discarded in the previous iteration thus changing the value of the counter from 5 to 6... etc....

Note that you do _not_ keep the values of the sub's variables between the calls of the sub. You have (or mean to have...) the actual counter outside the sub in $test_variable.

Therefore, if I wish to write a subroutine so that all its variables are scope within his subroutine and yet I want to retain the values of some of these variables for the next calling of this subroutine, I can write as follows but I just wonder is this the best way :-

It certainly isn't. You are using the package variable $_ as the actual counter, which is the worst possible solution I can think of. ;-)

Your _intention_ seems to be to use $test_variable as the actual counter, let testing_module() increment it by passing it to testing_module() each time you call the sub, and have the sub return the new value.

use strict;
use warnings;

my $anything = 0;
my $test_variable = 0;

while ($anything < 5){
 $anything +=1;
 $test_variable = &testing_module($test_variable) ;
}


sub testing_module {
  my $counter = $_;

You probably mean:

    my $counter = shift;

or

    my ($counter) = @_;

  if ($counter < 5) {
      $counter += 1;
  }
  $_ = $counter;

You do not want that line!

  print "Counter counting $counter\n";

    return $counter;

}

--
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/


Reply via email to