我想知道如何在Perl中取消定義哈希鍵的值。有人可以糾正我的代碼嗎?如何在Perl中未定義哈希鍵的值?
#!/usr/bin/perl
use strict;
use warnings;
my %hash;
undef($hash{"a"});
undef($hash{"b"});
print scalar values %hash; # i need here 0
print scalar keys %hash; # and here 2
我想知道如何在Perl中取消定義哈希鍵的值。有人可以糾正我的代碼嗎?如何在Perl中未定義哈希鍵的值?
#!/usr/bin/perl
use strict;
use warnings;
my %hash;
undef($hash{"a"});
undef($hash{"b"});
print scalar values %hash; # i need here 0
print scalar keys %hash; # and here 2
對方回答的約definedness與存在點是非常好的,但是如果你真的做想知道你總是可以做
print scalar grep { defined $_ } values %hash
undef($hash{"a"});
相當於
$hash{"a"}=undef;
所以你添加關鍵 'A' 與undef值。從哈希中刪除值使用「刪除」。
delete $hash{"a"};
對於同一個散列,'keys'和'values'不可能有不同的大小。您可以使用grep來過濾不需要的元素。
抱歉在我的問題中沒有描述性,現在我想更清楚了。謝謝。 – Alexandr 2009-12-22 00:54:42
undef $hash{$key};
這將定義值的數量undef這個鍵值:
print "E" if exists $hash{$key}; # will print E
print "D" if defined $hash{$key}; # will not print D
當然你的意思是'價值%哈希'。 – darch 2009-12-22 18:18:01
當然,我做到了。感謝抓住它:) – hobbs 2009-12-22 20:47:49
yeap,那正是我需要的! – Alexandr 2009-12-28 19:43:37