>Won't the vars in the "main" part of the
>script get destroyed upon completion?
The issue is not when things get cleaned up, it's how your program
communicates with itself. In general, you want to modularize your
code and that means that you use clean, simple ways of passing
information around. Globals are acceptable at times, otherwise they
wouldn't be in Perl. However, you should only use them when you
actually want to use them, which means when you don't mind if others
use them. Globals are very public because they're accessible to other
packages and subs.
The cleanest way to communicate with functions is through parameters,
and the cleanest way to communicate with other packages is usually
through accessor subs. Remember that when you pass information from
place to place, you don't want to worry about who might be using it.
That's why parameters are such a good way of passing information:
only you and your target know about them.
>I was under the impression that the reason for using
>"my" to declare a variable was to make it act like a
>local variable in a sub-routine or loop. Once you
>leave the sub or loop, the variable ceases to exist,
>thus making your script more efficient, easier to
>debug, and more flexible.
Not entirely true. For instance:
$b = do { my $a = "foo"; \$a; };
If my variables were like automatic variables in C, they would be
allocated on the stack. This code, then, would not set $b to a
reference to "foo". In perl, the reason 'my' variables are local is
because the name is associated with the block they were instantiated
in, and only has meaning in that block. That's why they're called
lexicals. As far as you and I are concerned, everything in Perl is
allocated on the heap, and we try not to worry exactly how things are
cleaned up.
> > use strict;
This is really helpful when you're writing normal code. I use strict
in all but a few modules that muck about with typeglobs because it
catches all manner of spelling mistakes and other goofups. You really
should declare all your variables one way or another because it helps
to make your code self-documenting.
Also, perl5.6 now has an "our" keyword. Consider using it for your
globals, because while use vars is great, the our keyword is much
closer to where the globals are actually used, so it helps make your
code clearer. You might do something like:
package SomePackage;
init();
sub init
{
our(%sound) = (dog=>'bark', cat=>'meow');
}
sub speak
{
my($pet) = @_;
our(%sound);
$sound{$pet};
}
--Ben Samuel
---
You are currently subscribed to perl-win32-users as: [[email protected]]
To unsubscribe, forward this message to
[EMAIL PROTECTED]
For non-automated Mailing List support, send email to
[EMAIL PROTECTED]