2009-07-03 71 views

回答

8

perldoc -f exists

   print "Exists\n" if exists $hash{$key}; 
       print "Defined\n" if defined $hash{$key}; 
       print "True\n"  if $hash{$key}; 

       print "Exists\n" if exists $array[$index]; 
       print "Defined\n" if defined $array[$index]; 
       print "True\n"  if $array[$index]; 

散列或數組元素可以是真 僅當它被定義,並且如果 它存在定義,但是反過來不 一定成立。

+0

存在並刪除數組元素有趣而不總是有用的屬性。如果你真的需要這些,你最好使用散列。 – ysth 2009-07-03 16:29:11

4

如果密鑰存在,它有一個值(即使這個值是undef)這樣:

my @keys_with_values = keys %some_hash; 
6

訂閱keys結果爲grepdefined

my @keys_with_values = grep { defined $hash{$_} } keys %hash; 

重讀你的問題,似乎你正在試圖找出你的散列中的任何值是否是未定義的,在這種情況下,你可以說類似

my @keys_without_values = grep { not defined $hash{$_} }, keys %hash; 
if (@keys_without_values) { 
    print "the following keys do not have a value: ", 
     join(", ", @keys_without_values), "\n"; 
} 
1

你的問題是不完整的。因此這種代碼可以是答案;-)

my %hash = (
    a => 'any value', 
    b => 'some value', 
    c => 'other value', 
    d => 'some value' 
); 
my @keys_with_some_value = grep $hash{$_} eq 'some value', keys %hash; 

編輯:我又重讀的問題,並決定這個問題的答案可能是:

sub all (&@) { 
    my $pred = shift(); 
    $pred->() or return for @_; 
    return 1; 
} 

my $all_keys_has_some_value = all {$_ eq 'some value'} values %hash; 
0

如果你只想知道是否所有值都已定義,或者任何未定義的值都可以這樣做:

sub all_defined{ 
    my($hash) = @_; 
    for my $value (values %$hash){ 
    return '' unless defined $value; # false but defined 
    } 
    return 1; #true 
} 
0

還有一種方法,使用each。 TIMTOWDI

while (my($key, $value) = each(%hash)) { 
     say "$key has no value!" if (not defined $value); 
} 
相關問題