SoFunction
Updated on 2025-04-07

The scope declaration in perl is introduced by our-my-local

To be honest, this thing is a bit troublesome, mainly because the statements in the book are very obscure, but it is not difficult to understand.
 
Our, "limiting the name to a certain range" is actually to clearly declare a "global variable". Although it is defined in a certain module or function, it can also be accessed outside. If it has been declared, use "our" again to indicate that the global one is used here, not a private or local variable with the same name.

Copy the codeThe code is as follows:

our $PROGRAM_NAME = "waiter";
{
my  $PROGRAM_NAME = "something";
our $PROGRAM_NAME = "server"; #The our here is the same as the outside, and is different from the previous sentence.
# The code called here sees "server"
}
# The code executed here still sees "server".

my , "Limit the name and value to a certain range", simply put, this variable can only be seen by modules or functions on this layer, and cannot be seen by those above the higher level or those below the lower level.
Copy the codeThe code is as follows:

sub greeting1{
    my ($hello) = "How are you do?";
    greeting2();
}
 
sub greeting2{
    print "$hello\n";
}
$hello = "How are you doing?";
greeting2();
greeting1();
greeting2();

Running results:
Copy the codeThe code is as follows:

How are you doing?
How are you doing?
How are you doing?

None of How are you do?, when calling greeting2 in greeting1, greeting2 cannot see the private $hello variable of greeting1, and can only see the global variable $hello outside
 
local, "limiting the value to a certain range", is also called "dynamic lexical range", which is a bit difficult to understand. My understanding is that the functions of this layer and the lower layer can see the variables of this layer, but the upper layer of this layer cannot. The scope is not only dependent on the functions of this layer, but also depends on the program length and depth of the next layer, so it is called "dynamic range".
Copy the codeThe code is as follows:

sub greeting1{
    local ($hello) = "How are you do?";
    greeting2();
}

sub greeting2{
    print "$hello\n";
}
$hello = "How are you doing?";
greeting2();
greeting1();
greeting2();


Running results:
Copy the codeThe code is as follows:

How are you doing?
How are you do?
How are you doing?

Is it different from using my? When greeting1 calls greeting2, greeting2 can see the local variable $hello of greeting1, and the external global variable is of course hidden.