Perl에서 문자열을 기반으로 전역 변수를 만들 수 있습니까?문자열을 기반으로 Perl 변수 이름을 만들려면 어떻게해야합니까?
예를 들어, 내가 같은 함수가 있다면 :
sub create_glob_var {
my ($glob_var_str) = @_;
# something like this (but not a hash access).
our ${$glob_var_str};
};
을 나는 전화가 좋아 :
create_glob_var("bar");
어떻게 실제로 $bar
라는 전역 변수를 만들 수 create_glob_var
을 수정할 수 있을까?
내 프로젝트에서 펄 5.8.5를 사용 중입니다.
편집
다음은 작동하지 않습니다
use strict;
BEGIN {
sub create_glob_var {
my ($glob_var_str) = @_;
no strict 'refs';
$$glob_var_str = undef; # or whatever you want to set it to
}
create_glob_var("bah");
};
$bah = "blah";
는 생산 :
Variable "$bah" is not imported at /nfs/pdx/home/rbroger1/tmp2.pl line 12. Global symbol "$bah" requires explicit package name at /nfs/pdx/home/rbroger1/tmp2.pl line 12. Execution of /nfs/pdx/home/rbroger1/tmp2.pl aborted due to compilation errors.
참고 내가 전역 변수를 사용하여 ozone depletion and male pattern baldness 원인이 있음을 알고 있습니다. 이미 전역 변수를 사용하여 완전히 감염된 일부 레거시 코드를 정리하려고합니다. 한 번에 하나의 리팩터 ...
서브 루틴은 전역 변수를 생성하지만 여전히 1) $ My :: Package :: bah = "blah"중 하나의 엄격한 방법으로 액세스해야합니다. 2) vars qw ($ bah); $ bah = "blah"또는 3) 우리의 $ bah = "blah". – Sean
이런 일은하지 마십시오. http://stackoverflow.com/questions/1549685/how-can-i-use-a-variable-as-a-variable-name-in-perl –
동의. 새로운 스칼라를 생성하는 대신 글로벌 해시를 사용하여 데이터를 저장하십시오 (전역 전역을 사용해야하는 경우). – Ether