• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Perl's keys() function

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
Perl's keys() function is used to iterate (loop) through the the keys of a HASH. The keys are returned as a list (array).
%contact = ('name' => 'Bob', 'phone' => '111-111-1111');
foreach $key (keys %contact) {
print "$key\n";
}
In the above example, we start with a simple hash of our contact Bob and his phone number. The keys function takes this regular hash as input, and is couched in a foreach loop. Here is the each function standing on it's own:
$key (keys %contact)
Every time the keys function is called, it grabs a key out of the hash and puts it in the $key string. When couched in the foreach statement it will loop through each element of the hash and pass the keys off to the print statement. The output of the program will be:
name
phone
There are a couple of things to keep in mind when using the keys function. Because of the way Perl works with hashes, the elements will be returned in random order. Also, the keys function does not remove the elements from the hash - the hash is unaffected by the looping process.
So let's say that you want to sort your hash by the keys as you're looping through them. It's a simple matter of setting the keys function inside a sort function like so:
%contact = ('name' => 'Bob', 'phone' => '111-111-1111');
foreach $key (sort(keys %contact)) {
print "$key\n";
}

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
使用Perl操作DBM数据库发布时间:2022-07-22
下一篇:
Perl:化繁为简发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap