Perl | keys() Function

keys() function in Perl returns all the keys of the HASH as a list. Order of elements in the List need not to be same always, but, it matches to the order returned by values and each function.

Syntax: keys(HASH)

Parameter:
HASH: Hash whose keys are to be printed

Return: For scalar context, it returns the number of keys in the hash whereas for List context it returns a list of keys.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
%hash = ('Ten' => 10,
         'Eleven' => 11,
         'Twelve' => 12,
         'Thirteen' => 13);
  
@values = values( %hash );
print("Values are  ", join("-", @values), "\n");
  
@keys = keys( %hash );
print("Keys are ", join("-", @keys), "\n");

chevron_right


Output:

Values are  11-12-13-10
Keys are Eleven-Twelve-Thirteen-Ten

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
%hash = ('Geek' => 1,
         'For' => 2,
         'Geeks' => 3);
  
@values = values( %hash );
print("Values are  ", join("-", @values), "\n");
  
@keys = keys( %hash );
print("Keys are ", join("-", @keys), "\n");

chevron_right


Output:

Values are  3-2-1
Keys are Geeks-For-Geek


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.