2014-07-08 35 views
1

這個問題似乎是一個範圍。帶有存在函數的行會拋出一個錯誤,指出它沒有接收散列作爲參數。我怎麼能這樣做傳遞給存在函數的值是我的散列?我定義了一個散列,但存在函數拋出一個錯誤,說它不是散列

#!/usr/bin/perl 

use warnings; 
use strict; 

open FH, 'test_out' or die $!; 

my %pn_codes =(); 

while(<FH>) { 
    if(/.*PN=(\d*)/) { 
     my $pn = $1; 
     if(exists %pn_codes{$pn}) { 
      print($pn, "exists"); 
     } else { 
      %pn_codes{$pn} = 1; 
     } 
    } 
} 
+1

嘗試'if(存在$ pn_codes {$ pn}){'改爲(將'%'改爲'$')。這裏也是:'$ pn_codes {$ pn} = 1;' – chilemagic

+0

實際上,錯誤表示它不是一個哈希*元素*。 – ikegami

回答

3

您必須在指定的標量exists$hash{key}

if (exists $pn_codes{$pn}) { 

但是,你基本上建立一個%seen風格散列可以簡化到:

while (<FH>) { 
    if (/.*PN=(\d*)/) { 
     my $pn = $1; 
     if (! $pn_codes{$pn}++) { 
      print($pn, "exists"); 
     } 
    } 
} 
+1

甚至可以避免全局變量:if(my($ pn)= /.* PN =(\ d *)/)' – ikegami

1

perl的diagnostics可能是有用的,

perl -Mdiagnostics -c script.pl 
exists argument is not a HASH or ARRAY element or a subroutine at c line 13 (#1) 
    (F) The argument to exists() must be a hash or array element or a 
    subroutine with an ampersand, such as: 

     $foo{$bar} 
     $ref->{"susie"}[12] 
     &do_something 

Uncaught exception from user code: 
     exists argument is not a HASH or ARRAY element or a subroutine at c line 13. 
at c line 13 
相關問題