Perl's keys() function

本文介绍Perl语言中利用keys函数遍历HASH的方法,并展示了如何通过sort函数按KEY排序遍历。此外还讨论了使用keys函数时需要注意的细节。
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";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值