2014-02-12 98 views
0

1.pm如何訪問的.pm文件變量的特等文件

package 1; 
our $Var= "hello"; 

2.pl

use 1; 
print "$Var\n"; 

我做什麼,我在上面2個文件1.pm2.pl提到。 in 2.pl我無法訪問該變量$Var

請你幫我一下嗎? 我應該如何在1.pm文件中聲明該變量(變量應該是全局變量)?

感謝,

+0

不要使用數字作爲包名和'$打印mypackage的:: Var' http://perldoc.perl.org/perlmod.html#Packages –

回答

2

摘要:包名稱不能以數字開始

詳細描述:

首先總是使用

use strict; 
use warnings; 
在腳本

。你會注意到一個錯誤信息:

Global symbol "$Var" requires explicit package name at 2.pl line 6. 
Execution of 2.pl aborted due to compilation errors. 

可以使用包名

$1::Var 

訪問,但你會得到

Bareword found where operator expected at 2.pl line 6, near "$1::Var" 
    (Missing operator before ::Var?) 
Bareword "::Var" not allowed while "strict subs" in use at 2.pl line 6. 
Execution of 2.pl aborted due to compilation errors. 

嘗試使用模塊名稱不開始與一個數字。例如,Mod.pm

package Mod; 

use strict; 
use warnings; 

our $Var= 'hello'; 
1; 

2.pl

use warnings; 
use strict; 

use Mod; 

print $Mod::Var . "\n"; 

1; 

perlmod

只有標識符以字母(或下劃線)開始被存儲在一個包的符號表。

雖然不是強制性的,但通常(強烈建議)大寫包名稱。例如,請參閱Perl::Critic::Policy::NamingConventions::Capitalization

+0

你的回答不能正確地運行 – JackXu

+0

@JackXu爲什麼?運行'perl 2.pl'給我如預期'你好' – Matteo

+0

我已經運行它。給我兩個錯誤 – JackXu

1

您的問題與變量聲明的文件無關,但與使用package關鍵字時所使用的名稱空間無關。另外,請確保您的名稱空間不以數字開頭。來自perlmod(1):

只有以字母(或下劃線)開頭的標識符 存儲在包的符號表中。

相關問題