Perl by Example - 02

1837 단어 perl

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 "
"; 3 foreach $key ( sort keys(%weekday) ){print $key ;} print "
"; (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.
  • 좋은 웹페이지 즐겨찾기