sandyago has asked for the wisdom of the Perl Monks concerning the following question:
|
|---|
| Replies are listed 'Best First'. | |||
|---|---|---|---|
|
Re: my $a and our $a
by Athanasius (Archbishop) on Jan 06, 2016 at 06:53 UTC | |||
Hello sandyago, I think this is well explained in Ovid’s tutorial 'our' is not 'my'. Read that through a few times, study it, then come back if you need clarification. BTW, $a is a poor choice of variable name here, as $a and $b are special (global) variables used by sort. It’ll be less confusing to use something like $x instead. Hope that helps,
| [reply] [d/l] [select] | ||
|
Re: my $a and our $a
by Marshall (Canon) on Jan 06, 2016 at 07:15 UTC | |||
Almost all of your variables should be "my whatever"...that means 99.9%. These are lexically scoped variables within a single compilation unit. The addresses of these variables are not fixed, they are allocated on the stack. The same name can be reused again and again within different loops. "my $name" in one loop is not the same as "my $name" in another loop. An "our" variable is different. This is like a C static. This variable is global and goes into a special symbol table. These variables can be accessed by other modules (there is no way to do that with a "my" variable). "our" variables should be used very sparingly and for good reasons. | [reply] | ||
|
Re: my $a and our $a
by vinoth.ree (Monsignor) on Jan 06, 2016 at 08:00 UTC | |||
my is a way to declare, none package variables, which are private,non-global variables separate from any package. So that the variable cannot be accessed in the form of $PackageName::variable our variables are, package variables, global variables and not private, they can be accessed outside the package with the qualified namespace, as $PackageName::variable Declaring a variable with our allows you to predeclare variables in order to use them under use strict without getting typo warnings or compile-time errors. Since Perl 5.6, it has replaced the obsolete use vars, which was only file-scoped, and not lexically scoped as is our. For example, the formal, qualified name for variable $x inside package main is $main::x. Declaring our $x allows you to use the bare $x variable without penalty (i.e., without a resulting error), in the scope of the declaration, when the script uses use strict or use strict "vars". The scope might be one, or two, or more packages, or one small block. Example:
All is well. I learn by answering your questions... | [reply] [d/l] [select] | ||