在标量上下文中评估 Perl 中的哈希值的原因是什么?
我意识到在标量上下文中评估 Perl 中的数组很有用:它会产生#个元素。
但是能够在标量上下文中计算哈希值有什么实际用途呢?例如
我的 $scalar_value = %hash;
标量(%hash)
据我了解,它会生成一个类似“3/4
”的字符串,提供有关哈希内部的一些信息,似乎只对调试有用。
I realize that evaluating an array in Perl in a scalar context is useful: it results in a # of elements.
But what is the practical use of being able to evaluate a hash in a scalar context? e.g.
my $scalar_value = %hash;
scalar(%hash)
As far as I understand, it produces a string like "3/4
" giving some information about the internals of the hash that appears to only be useful for debugging.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它生成一个值,该值可用作 TRUE/FALSE 标志来了解哈希是否为空(无键)。
例如:
if
强制表达式进入标量上下文,因为它用作布尔表达式。这与在标量上下文中使用 @array 来测试空性的概念非常相似:
It produces a value that can be used as a TRUE/FALSE flag to know if the hash is empty (no keys).
As an example:
if
forces the expression into a scalar context because of its use as a boolean expression.It's a very similar concept to using
@array
in a scalar context to test for emptiness:标量(%hash) 可让您检查哈希算法是否正常工作。如果您有 1,000 个密钥,并且您看到类似 2/16 的内容,则意味着所有密钥仅解析为 16 个分配的存储桶中的 2 个。这意味着您的所有键都非常相似并导致大量冲突,从而导致存储桶中的长时间连续搜索。
默认存储桶计数为 8
用 1000 个存储桶预存储哈希(到最接近的 2 的幂),
当您为 Perl OO 祝福哈希时,这也会有所帮助。
如果您知道会有很多密钥,则可以加快速度。
The scalar(%hash) lets you check if the hashing algorithm is working correctly. If you have 1,000 keys and you see something like 2/16 that means all the keys are resolving to only 2 of the 16 allotted buckets. This means all your keys are very similar and causing lots of collisions, which results in long sequential searches in the bucket.
Default bucket count is 8
Prestash the hash with 1000 buckets (to the nearest power of 2)
This also helps out when you bless an hash for perl OO.
You can speed things up if you know there will be a lot of keys.