如何清除 Perl 哈希 [英] How to clear a Perl hash

查看:38
本文介绍了如何清除 Perl 哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们像这样定义一个匿名哈希:

Let's say we define an anonymous hash like this:

my $hash = {};

然后使用哈希.然后是时候清空或清除哈希重用.经过一番谷歌搜索,我发现:

And then use the hash afterwards. Then it's time to empty or clear the hash for reuse. After some Google searching, I found:

%{$hash} = () 

和:

undef %{$hash}

两者都能满足我的需求.两者有什么区别?它们清空哈希的方法是否相同?

Both will serve my needs. What's the difference between the two? Are they both identical ways to empty a hash?

推荐答案

是的,它们完全相同.两者都从表中删除任何现有的键和值,并将哈希设置为空列表.

Yes, they are absolutely identical. Both remove any existing keys and values from the table and sets the hash to the empty list.

参见perldoc -f undef:

undef EXPR
undef   取消定义 EXPR 的值,该值必须是左值.仅使用在标量值、数组(使用@")、散列(使用%")、子例程(使用&"),或类型团(使用*")...
示例:

undef EXPR
undef   Undefines the value of EXPR, which must be an lvalue. Use only on a scalar value, an array (using "@"), a hash (using "%"), a subroutine (using "&"), or a typeglob (using "*")...
Examples:

               undef $foo;  
               undef $bar{'blurfl'};      # Compare to: delete $bar{'blurfl'};  
               undef @ary;  
               undef %hash;

但是,您不应该使用 undef 删除除标量之外的任何值.对于其他变量类型,将其设置为该类型的空"版本——例如对于数组或散列,@foo = ();%bar = ();

However, you should not use undef to remove the value of anything except a scalar. For other variable types, set it to the "empty" version of that type -- e.g. for arrays or hashes, @foo = (); %bar = ();

这篇关于如何清除 Perl 哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆