David Granas wrote:
Hi,

Im just learning Perl and was a little confused with why I couldnt prevent my subroutines from reading variables from the main program. Here is an example:

use strict;

my $var = 1;

test();

sub test
{
     print $var;
}

I had thought that a my variable would not be able to be read by the subroutine, but it can still see it. So my question is how can I prevent subroutines from having access to variables in the main program. Thanks for any help,


Common mistake. 'my' gives a variable lexical scoping, which basically defines where the variable is visible. So in a sense it appears as a 'main' variable only because your subroutine and the my'ed variable are in the same file. If you were to move your subroutine into a library file and then call the sub it would not be visible in the sub. This is one reason why people often prefer to put all subs in a library and have only a main in the script. It is also why sometimes you will see a variable's scope specifically controlled by braces, though in this case it will not help, here is an example:


{
  my $count;
  foreach my $file (@files) {
     # do something to file
     $count++;
  }
}

$count is not visible outside the braces even in the same file. To create a truly 'main' variable (which you don't want to do *usually*) you would need to put that variable in the package list for the 'main' by using an 'our' in the main package. Then the variable would be accessible with $main::, but your $var is not, so it is not, strictly speaking, a 'main' or global.

Excellent reading on the scoping of variables in Perl can be found here:

http://perl.plover.com/FAQs/Namespaces.html

http://danconia.org


-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]



Reply via email to