vivion34 发表于 2017-5-18 10:27:19

Perl by Example

  


5.5. Hash (Associative Array)
Functions

5.5.1. The keys Function

The keys
function returns, in random order, an array whose elements are the keys of a
hash (see "The values Function" and "The each
Function").
  




Format

keys(ASSOC_ARRAY)
keys ASSOC_ARRAY




Example 5.53.
  




(In Script)
# The keys function returns the keys of a hash
1   %weekday= (
'1'=>'Monday',
'2'=>'Tuesday',
'3'=>'Wednesday',
'4'=>'Thursday',
'5'=>'Friday',
'6'=>'Saturday',
'7'=>'Sunday',
);
2   foreach $key ( keys(%weekday) ){print "$key ";}
print "\n";
3   foreach $key ( sort keys(%weekday) ){print $key ;}
print "\n";
(Output)
2   7 1 2 3 4 5 6
3   1 2 3 4 5 6 7


Explanation


[*]
The hash %weekday is assigned
keys and values.

[*]
For each value in %weekday, call
the keys function to get
the key. Assign the key value to the scalar $key and print it in random
order.

[*]
Now the keys are sorted and
printed.







页: [1]
查看完整版本: Perl by Example