2013-01-17 75 views
1

我無法理解引用如何在子文件中使用散列。perl修改子文件中的散列

在這段代碼中,我試圖改變%confighandleOptions()子程序內:

sub handleOption; 

my %config = ( gpg => "", 
       output => "", 
       pass => "", 
       host => "", 
       type => ""); 

handleOptions(\%config); 
print "\n"; 
print Dumper \%config; 

sub handleOptions 
{ 
    my ($gpgpath,$type,$pass,$host); 
    my [email protected]_; 

    GetOptions ("gpg=s" => \$gpgpath, 
       "type=s" => \$type, 
       "host=s" => \$type, 
       "pass=s"=>\$pass); 
    $pConfig->{'gpg'} = $gpgpath; 
    $pConfig->{'type'} = $type; 
    $pConfig->{'pass'} = $pass; 
    $pConfig->{'host'} = $host; 
    print Dumper %$pConfig; 
} 

下面是輸出的時候,我給--gpg='/home/daryl/gpg/pass.gpg的選項CLI:

$VAR1 = 'pass'; 
$VAR2 = undef; 
$VAR3 = 'gpg'; 
$VAR4 = '/home/daryl/gpg/pass.gpg'; 
$VAR5 = 'type'; 
$VAR6 = undef; 
$VAR7 = 'host'; 
$VAR8 = undef; 

$VAR1 = { 
      'pass' => '', 
      'gpg' => '', 
      'type' => '', 
      'output' => '', 
      'host' => '' 
     }; 

我應該如何着手?

+5

試試這個:'我的($ pConfig)= @_;' –

+4

完美演示總是使用strict和warnings的價值。 – TLP

+1

'嚴格使用;使用警告;儘管如此,'不會幫助他處理子程序聲明不匹配。 – smithfarm

回答

4

如果您是use strictuse warnings,您會看到有關使用標量作爲散列引用的錯誤消息。這將提示你的問題是在這條線:

my [email protected]_; 

你分配陣列@_的標量環境變量$pConfig。這意味着$pConfig正在存儲數組@_中的元素數量。

相反,你可以這樣做:

my ($pConfig) = @_;爲KerrekSB建議,或:

my $pConfig = shift;(其中shift@_ S也可以自動)

看看perldoc perldata的更多信息,調用非標量環境中的標量。另外,除非你正在編寫一行或一個簡短的廢棄腳本,請務必始終使用use strictuse warnings

+1

非常感謝你,所有解決了我的問題:)我真的是新的Perl,我仍然經常忘記設置這些「嚴格/警告」行 – Azryel

+0

@阿茲里爾 - 不客氣。我建議選擇一個[Learning Perl](http://www.amazon.com/Learning-Perl-Randal-L-Schwartz/dp/1449303587)的副本,以獲得相對較少的閱讀內容,這會讓你啓動並運行,和/或[Programming Perl](http://www.amazon.com/Programming-Perl-Unmatched-processing-scripting/dp/0596004923/ref=sr_1_1?s=books&ie=UTF8&qid=1358441774&sr=1-1&keywords=programming + perl)這是一本厚得多的書,但更全面。 – 2013-01-17 16:56:36