如何在 Perl 哈希中计算键的数量?


有时候我们想知道哈希中存在多少键值对。这些键值对的数量也称为哈希的大小。在 Perl 中,我们可以使用“scalar”关键字或“keys”关键字来查找 Perl 哈希中键的数量。

在本教程中,我们将探讨两个 Perl 示例,我们将计算哈希中键的数量。

示例

考虑以下代码。在此代码中,我们声明了一个名为“countries”的哈希,在这个哈希中,我们有不同的国家,每个国家都有不同的值。我们使用“keys”关键字来计算哈希中键的数量。

Open Compiler
# create the Perl hash $countries{'India'} = 12.00; $countries{'China'} = 1.25; $countries{'Russia'} = 3.00; $countries{'USA'} = 9.1; # get the hash size $size = keys %countries; # print the hash size print "The hash contains $size key-value pairs.\n";

输出

如果您在 Perl 编译器中运行上述代码,那么我们将在终端中获得以下输出。

The hash contains 4 key-value pairs.

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例

现在让我们看看如何使用“scalar”关键字来找出哈希中键的数量。考虑以下代码。

在此代码中,我们声明了一个名为“countries”的哈希,在这个哈希中,我们有不同的国家,每个国家都有不同的值。然后我们使用“scalar”关键字来找出哈希中存在的键的数量。

Open Compiler
# create the Perl hash $countries{'India'} = 12.00; $countries{'China'} = 1.25; $countries{'Russia'} = 3.00; $countries{'USA'} = 9.1; # get the hash size $size = scalar % countries; # print the hash size print "The hash contains $size key-value pairs.\n";

输出

如果您在 Perl 编译器中运行上述代码,那么我们将在终端中获得以下输出。

The hash contains 4 key-value pairs.

更新于:2023年4月4日

2K+ 次浏览

启动您的职业生涯

通过完成课程获得认证

开始
广告