Perl에서 나와 우리의 차이점은 무엇입니까?
나는 my
Perl에 무엇이 있는지 안다 . 정의 된 블록의 범위에만 존재하는 변수를 정의합니다. 무엇을 our
합니까? our
와는 어떻게 다릅니 my
까?
좋은 질문 : 어떻게 our
다를 my
무엇을 않습니다 our
합니까?
요약하자면:
Perl 5부터 사용 가능 my
하며 선언 방법입니다.
- 비 패키지 변수
- 은밀한,
- 새 ,
- 비전 역 변수
- 모든 패키지와 분리하십시오. 따라서 변수 는 형식으로 액세스 할 수 없습니다
$package_name::variable
.
반면에 our
변수는 다음과 같습니다.
- 패키지 변수를 자동으로
- 전역 변수
- 확실히 사적인 것이 아닙니다 .
- 그것들은 반드시 새로운 것이 아니며; 그리고 그들은
- 정규화 된 네임 스페이스를 사용하여 패키지 외부 (또는 어휘 범위) 외부에서 액세스 할 수 있습니다
$package_name::variable
.
변수 선언 our
을 사용하면 use strict
오타 경고 나 컴파일 타임 오류없이 변수를 사용하기 위해 변수를 미리 선언 할 수 있습니다. Perl 5.6부터는 use vars
파일 범위 만 있고 어휘 범위가 없는 구식을 대체했습니다 our
.
예를 들어, 변수 $x
inside의 정규화 된 이름 package main
은 $main::x
입니다. 선언은 our $x
당신이 베어 사용할 수 있습니다 $x
선언, 스크립트 사용의 범위에서, (그 결과의 오류없이, 즉) 위약금없이 변수를 use strict
나 use strict "vars"
. 범위는 하나 또는 둘 이상의 패키지 또는 하나의 작은 블록 일 수 있습니다.
cartman과 Olafur의 PerlMonks와 PerlDoc 링크는 훌륭한 참고 자료입니다-아래는 요약에서 내 균열입니다.
my
변수는 s에 {}
있지 않은 경우 동일한 파일에 의해 정의 되거나 동일한 파일 내에 정의 된 단일 블록 내에서 어휘 범위가 지정됩니다 {}
. 동일한 어휘 범위 / 블록 외부에 정의 된 패키지 / 서브 루틴에서는 액세스 할 수 없습니다.
our
변수는 패키지 / 파일 내에서 범위가 지정 되며 적절한 네임 스페이스를 앞에 추가하여 패키지간에 use
또는 require
패키지 / 파일 이름 충돌이 해결 되는 모든 코드에서 액세스 할 수 있습니다 .
반올림하기 위해 local
변수는 "동적"범위를 가지며 my
동일한 블록 내에서 호출되는 서브 루틴에서도 액세스 할 수 있다는 점 에서 변수와 다릅니다 .
예를 들면 :
use strict;
for (1 .. 2){
# Both variables are lexically scoped to the block.
our ($o); # Belongs to 'main' package.
my ($m); # Does not belong to a package.
# The variables differ with respect to newness.
$o ++;
$m ++;
print __PACKAGE__, " >> o=$o m=$m\n"; # $m is always 1.
# The package has changed, but we still have direct,
# unqualified access to both variables, because the
# lexical scope has not changed.
package Fubb;
print __PACKAGE__, " >> o=$o m=$m\n";
}
# The our() and my() variables differ with respect to privacy.
# We can still access the variable declared with our(), provided
# that we fully qualify its name, but the variable declared
# with my() is unavailable.
print __PACKAGE__, " >> main::o=$main::o\n"; # 2
print __PACKAGE__, " >> main::m=$main::m\n"; # Undefined.
# Attempts to access the variables directly won't compile.
# print __PACKAGE__, " >> o=$o\n";
# print __PACKAGE__, " >> m=$m\n";
# Variables declared with use vars() are like those declared
# with our(): belong to a package; not private; and not new.
# However, their scoping is package-based rather than lexical.
for (1 .. 9){
use vars qw($uv);
$uv ++;
}
# Even though we are outside the lexical scope where the
# use vars() variable was declared, we have direct access
# because the package has not changed.
print __PACKAGE__, " >> uv=$uv\n";
# And we can access it from another package.
package Bubb;
print __PACKAGE__, " >> main::uv=$main::uv\n";
범위 지정에 대처 하는 것은 Perl 범위 지정 규칙에 대한 좋은 개요입니다. our
본문에서 다루지 않을 정도로 오래 되었습니다. 끝에 있는 참고 섹션에서 설명합니다.
이 기사에서는 패키지 변수 및 동적 범위와 어휘 변수 및 어휘 범위와 다른 점에 대해 설명합니다.
my is used for local variables, where as our is used for global variables. More reading over Variable Scoping in Perl: the basics .
It's an old question, but I ever met some pitfalls about lexical declarations in Perl that messed me up, which are also related to this question, so I just add my summary here:
1. definition or declaration?
local $var = 42;
print "var: $var\n";
The output is var: 42
. However we couldn't tell if local $var = 42;
is a definition or declaration. But how about this:
use strict;
use warnings;
local $var = 42;
print "var: $var\n";
The second program will throw an error:
Global symbol "$var" requires explicit package name.
$var
is not defined, which means local $var;
is just a declaration! Before using local
to declare a variable, make sure that it is defined as a global variable previously.
But why this won't fail?
use strict;
use warnings;
local $a = 42;
print "var: $a\n";
The output is: var: 42
.
That's because $a
, as well as $b
, is a global variable pre-defined in Perl. Remember the sort function?
2. lexical or global?
I was a C programmer before starting using Perl, so the concept of lexical and global variables seems straightforward to me: just corresponds to auto and external variables in C. But there're small differences:
In C, an external variable is a variable defined outside any function block. On the other hand, an automatic variable is a variable defined inside a function block. Like this:
int global;
int main(void) {
int local;
}
While in Perl, things are subtle:
sub main {
$var = 42;
}
&main;
print "var: $var\n";
The output is var: 42
, $var
is a global variable even it's defined in a function block! Actually in Perl, any variable is declared as global by default.
The lesson is to always add use strict; use warnings;
at the beginning of a Perl program, which will force the programmer to declare the lexical variable explicitly, so that we don't get messed up by some mistakes taken for granted.
The perldoc has a good definition of our.
Unlike my, which both allocates storage for a variable and associates a simple name with that storage for use within the current scope, our associates a simple name with a package variable in the current package, for use within the current scope. In other words, our has the same scoping rules as my, but does not necessarily create a variable.
This is only somewhat related to the question, but I've just discovered a (to me) obscure bit of perl syntax that you can use with "our" (package) variables that you can't use with "my" (local) variables.
#!/usr/bin/perl
our $foo = "BAR";
print $foo . "\n";
${"foo"} = "BAZ";
print $foo . "\n";
Output:
BAR
BAZ
This won't work if you change 'our' to 'my'.
print "package is: " . __PACKAGE__ . "\n";
our $test = 1;
print "trying to print global var from main package: $test\n";
package Changed;
{
my $test = 10;
my $test1 = 11;
print "trying to print local vars from a closed block: $test, $test1\n";
}
&Check_global;
sub Check_global {
print "trying to print global var from a function: $test\n";
}
print "package is: " . __PACKAGE__ . "\n";
print "trying to print global var outside the func and from \"Changed\" package: $test\n";
print "trying to print local var outside the block $test1\n";
Will Output this:
package is: main
trying to print global var from main package: 1
trying to print local vars from a closed block: 10, 11
trying to print global var from a function: 1
package is: Changed
trying to print global var outside the func and from "Changed" package: 1
trying to print local var outside the block
In case using "use strict" will get this failure while attempting to run the script:
Global symbol "$test1" requires explicit package name at ./check_global.pl line 24.
Execution of ./check_global.pl aborted due to compilation errors.
Just try to use the following program :
#!/usr/local/bin/perl
use feature ':5.10';
#use warnings;
package a;
{
my $b = 100;
our $a = 10;
print "$a \n";
print "$b \n";
}
package b;
#my $b = 200;
#our $a = 20 ;
print "in package b value of my b $a::b \n";
print "in package b value of our a $a::a \n";
#!/usr/bin/perl -l
use strict;
# if string below commented out, prints 'lol' , if the string enabled, prints 'eeeeeeeee'
#my $lol = 'eeeeeeeeeee' ;
# no errors or warnings at any case, despite of 'strict'
our $lol = eval {$lol} || 'lol' ;
print $lol;
Let us think what an interpreter actually is: it's a piece of code that stores values in memory and lets the instructions in a program that it interprets access those values by their names, which are specified inside these instructions. So, the big job of an interpreter is to shape the rules of how we should use the names in those instructions to access the values that the interpreter stores.
On encountering "my", the interpreter creates a lexical variable: a named value that the interpreter can access only while it executes a block, and only from within that syntactic block. On encountering "our", the interpreter makes a lexical alias of a package variable: it binds a name, which the interpreter is supposed from then on to process as a lexical variable's name, until the block is finished, to the value of the package variable with the same name.
The effect is that you can then pretend that you're using a lexical variable and bypass the rules of 'use strict' on full qualification of package variables. Since the interpreter automatically creates package variables when they are first used, the side effect of using "our" may also be that the interpreter creates a package variable as well. In this case, two things are created: a package variable, which the interpreter can access from everywhere, provided it's properly designated as requested by 'use strict' (prepended with the name of its package and two colons), and its lexical alias.
Sources:
- http://perldoc.perl.org/functions/our.html
- http://perldoc.perl.org/perlsub.html#Private-Variables-via-my()
참고URL : https://stackoverflow.com/questions/845060/what-is-the-difference-between-my-and-our-in-perl
'Programing' 카테고리의 다른 글
반응 성분을 다른 반응 성분으로 전달하여 첫 번째 성분의 내용을 포함시키는 방법은 무엇입니까? (0) | 2020.05.19 |
---|---|
Tornado 사용시기, Twisted / Cyclone / GEvent / 기타 사용시기 (0) | 2020.05.19 |
동적으로 삽입 된 iframe의 jQuery .ready (0) | 2020.05.19 |
파일 이름이 포함 된 경로에서 파일 이름없이 전체 경로 가져 오기 (0) | 2020.05.19 |
매크로에서 익명 클래스의 메소드를 사용하여 구조 유형 가져 오기 (0) | 2020.05.18 |