Control your arrays and hashes using these Perl functions
Takeaway: This document explores some of the most useful Pearl functions for manipulating arrays and hashes, with brief explanations of how each one works and when it should be used.
Just because Perl is known for its string processing capabilities, doesn't mean that's all there is to it. The language comes with a fair number of functions to process and manipulate other data structures as well, including the ever-popular arrays and hashes. This document explores some of the most useful functions in this category, with brief explanations of how each one works and when it should be used.
|
Function |
Explanation |
Example |
| scalar(@arr) |
This function forces an array or hash to be interpreted as a scalar. This is useful to find out the number of elements in an array or hash. Use this function to find out the size of an array or hash, preparatory to iterating over it in a loop and processing its contents. |
Code: #!/bin/perl # define array @data = ('apple', 'peach', 'banana'); # get size print "The array has " . scalar(@data) . " elements"; Output: The array has 3 elements |
| exists $hash{$key} |
This function can be used to test if a particular key exists in a hash. |
Code: #!/bin/perl # define hash %data = ('king' => 'queen', 'prince' => 'princess'); # check if key exists if (exists $data{'king'}) { print "Found!"; } Output: Found! |
| push(@arr, $val) |
This function adds a new element to the end of an array. |
Code: #!/bin/perl # define array @data = ('a', 'b', 'c'); # add element push(@data, 'd'); Output: a b c d |
| pop(@arr) |
This function removes an element from the end of the array. |
Code: #!/bin/perl # define array @data = ('a', 'b', 'c'); # add element pop(@data); print "@data "; Output: a b |
| unshift(@arr, $val) |
This function adds a new element to the beginning of an array. |
Code: #!/bin/perl # define array @data = ('a', 'b', 'c'); # add element unshift(@data, 'z'); print "@data "; Output: z a b c |
| shift(@arr) |
This function removes an element from the beginning of the array. |
Code: #!/bin/perl # define array @data = ('a', 'b', 'c'); # remove element shift(@data); print "@data "; Output: b c |
| splice(@arr, $offset, $length, @arr2) |
This function removes a segment of an array, starting from the element at position $offset and continuing until $length elements have been removed. If the optional @arr2 argument is present, the extracted segment is replaced with the element of array @arr2. Use this function to extract subsets of an array, or to replace elements in an array with new values. |
Code: #!/bin/perl # define array @data = ('king', 'queen', 'knight', 'bishop'); # remove middle elements splice(@data, 1, 2); print "@data "; Output: king bishop |
| delete $hash{$key} |
This function deletes a key from a hash, together with its associated value. Use this function to remove elements from a hash. |
Code: #!/bin/perl # define hash %data = ('king' => 'queen', 'prince' => 'princess'); # remove element with key 'king' delete $data{'king'}; |
| split($delim, $str) |
This function decomposes a string by splitting it on delimited $delim and returns the individual components as elements of a numerically-indexed array. These elements can then be processed in a loop. Use this function to split comma-delimited lists into independent array elements. |
Code: #!/bin/perl # define string $str = "cat,hog,dog,log"; # split string on comma delimiter @words = split(",", $str); foreach $w (@words) { print "$w\n"; } Output: cat hog dog log |
| join($sep, @arr) |
This function joins the various elements of an array into a single string, using the value of $sep to separate them from each other. Use this function to create a single string from multiple independent array elements, using spaces, commas or other separators to glue them together. |
Code: #!/bin/perl # define array @data = ("Harry", "Joan", "Tom"); # create string from array print join(" and ", @data) . " are friends"; Output: Harry and Joan and Tom are friends |
| keys(%hash) |
This function returns the keys of a hash as a numerically-indexed array. The function is the counterpart of the values() function, discussed next. Use this function to extract the keys of a hash into a separate data structure for further processing. |
Code: #!/bin/perl # define hash %data = ('a' => 'apple', 'b' => 'bat', 'c' => 'cat'); # get and print hash keys @keys = keys(%data); Output: c a b |
| values(%hash) |
This function returns the values of a hash as a numerically-indexed array. The function is the counterpart of the keys() function, discussed previously. Use this function to extract the values of a hash into a separate data structure for further processing. |
Code: #!/bin/perl # define hash %data = ('a' => 'apple', 'b' => 'bat', 'c' => 'cat'); # get and print hash keys @vals = values(%data); foreach $v (@vals) { print "$v "; } Output: cat apple bat |
| reverse(@arr) |
This function reverses the order of elements of an array, placing the last element first and vice-versa. Use this function to re-sort an array's elements in the opposite direction to their current sort. |
Code: #!/bin/perl # define array @data = ('apple', 'peach', 'banana'); # reverse array @rev = reverse(@data); print "@rev "; Output: banana peach apple |
| sort(@arr) |
This function can be used to sort the elements of an array or hash. By default, this function sorts using standard string comparison rules; however, you can override this by passing it the name of a custom sorting subroutine. Use this function to reset the internal order of elements of an array, or to arrange elements alphabetically, numerically or in a custom order. |
Code: #!/bin/perl # define hash @data = ('oranges', 'peaches', 'grapes', 'apples', 'lemons'); # sort alphabetically @sorted = sort(@data); print "@sorted "; Output: apples grapes lemons oranges peaches |
Print/View all Posts Comments on this article
SponsoredWhite Papers, Webcasts, and Downloads
- 2008 IT Salary and Skills Report Global Knowledge
- 2007 IT Salary and Skills Survey: What Impacts Salaries? Global Knowledge
- The Case for Virtual Local Area Networks (VLANs) Global Knowledge
- ITIL Version 3.0 -- What It Means to You Global Knowledge
- TCP/IP Troubleshooting Global Knowledge
Article Categories
- Security
- Security Solutions, IT Locksmith
- Networking and Communications
- E-mail Administration NetNote, Cisco Routers and Switches
- CIO and IT Management
- Project Management, CIO Issues, Strategies that Scale
- Desktops, Laptops & OS
- Windows 2000 Professional, Microsoft Word, Microsoft Excel, Microsoft Access, Windows XP,
- Data Management
- Oracle, SQL Server
- Servers
- Windows NT, Linux NetNote, Windows Server 2003
- Career Development
- Geek Trivia
- Software/Web Development
- Web Development Zone, Visual Basic, .NET

