The Wayback Machine - https://web.archive.org/web/20241009154329/https://www.geeksforgeeks.org/perl-hash/
Open In App

Perl Hash

Last Updated : 03 Sep, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A hash is a set of key-value pairs. Perl stores elements of a hash such that it searches for the values based on its keys. Hash variables start with a ‘%’ sign. 

Perl requires the keys of a hash to be strings, whereas the values can be any scalars. These values can either be a number, string or reference. If non-string values are used as the keys, it gives an unexpected result. 

A hash key must be unique. If a new key-value pair is added to a hash and that key is existing then its corresponding value is overwritten. 

Creating Hashes

There are many ways to initialize a hash variable which are shown below:

  • The value is directly assigned as shown below and data is added to an existing hash.
$stud{'Comp'} = 45;
$stud{'Inft'} = 42;
$stud{'Extc'} = 35;
  • Another way is by using list which gets converted to hash by taking individual pairs. The first element of the pair is used as the key, and the second is taken as the value.
%stud = ('Comp', 45, 'Inft', 42, 'Extc', 35);
  • One way is using => to indicate the key/value pairs as shown below :
%stud = ('Comp' => 45, 'Inft' => 42, 'Extc' => 35);
  • Another way of doing the same thing is as shown below. Here all the keys are preceded by hyphen (-) and so no quotation is required around them. Hash can be build using this method only if there are no spaces in the word.
%stud = (-Comp => 45, -Inft => 42, -Extc => 35);
Accessing Hash Elements

To access the individual element from the hash, variable is prefixed with a dollar sign ($) and then append the element key within curly braces after the name of the variable. 

The below Example illustrates all of the methods of Hash creation as explained above: 

Example :  

Perl




#!/usr/bin/perl
 
# Initializing Hash1 by
# directly assigning values
$stud1{'Comp'} = 10;
$stud1{'Inft'} = 20;
$stud1{'Extc'} = 30;
 
# printing elements of stud
print "Printing values of Hash1\n";
print "$stud1{'Comp'}\n";
print "$stud1{'Inft'}\n";
print "$stud1{'Extc'}\n";
 
# Initializing Hash2 by taking
# individual pairs
%stud2 = ('Comp', 15, 'Inft', 18, 'Extc', 22);
 
# Extracting values using keys
print "\nPrinting values of Hash2\n";
print "computer = $stud2{'Comp'}";
print "\ninft = $stud2{Inft}";
print "\nextc = $stud2{'Extc'}\n";
 
 
# Initializing Hash3 using '=>'
%stud3 = ('Comp' => 45, 'Inft' => 42, 'Extc' => 35);
 
# printing elements of stud3
print "\nPrinting values of Hash3\n";
print "$stud3{'Comp'}\n";
print "$stud3{'Inft'}\n";
print "$stud3{'Extc'}\n";
 
# Initializing Hash4 using hyphen(-)
%stud4 = (-Comp => 5, -Inft => 15, -Extc => 25);
 
# Printing elements of stud4
print "\nPrinting values of Hash4\n";
print "$stud4{'-Comp'}\n";
print "$stud4{'-Inft'}\n";
print "$stud4{'-Extc'}";


Output: 

Printing values of Hash1
10
20
30

Printing values of Hash2
computer = 15
inft = 18
extc = 22

Printing values of Hash3
45
42
35

Printing values of Hash4
5
15
25

 

Extracting Keys and Values

Sometimes there is a need to extract keys and values of a hash to perform various operations on it. Operations like element modification, deletion, addition, etc. Hash allows to extract these keys and values with the use of inbuilt functions. 
Getting a list of all of the keys from a hash can be done using keys function.

Syntax: keys %HASH 
Returns an array of all the keys present in the HASH

Example:  

Perl




# Initializing Hash with Key-Value pairs
%stud = ('Comp' => 45, 'Inft' => 42, 'Extc' => 35);
 
# Extracting keys from hash
@Key_array = keys %stud;
 
# Printing the extracted keys
print "Keys are :\n";
print "$Key_array[0]\n";
print "$Key_array[1]\n";
print "$Key_array[2]\n";


Output: 

Keys are :
Comp
Extc
Inft

Similarly, values function is used to get a list of all the values.  

Syntax: values %HASH 
Returns an array with all the values of HASH

Example:  

Perl




# Initializing Hash with Key-Value pairs
%stud = ('Comp' => 45, 'Inft' => 42, 'Extc' => 35);
 
# Extracting values from hash
@value_array = values %stud;
 
# Printing the extracted values
print "Values are :\n";
print "$value_array[0]\n";
print "$value_array[1]\n";
print "$value_array[2]\n";


Output: 

Values are :
45
35
42

 



Previous Article
Next Article

Similar Reads

Perl | Basic Syntax of a Perl Program
Perl is a general purpose, high level interpreted and dynamic programming language. Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar
10 min read
Sorting Hash in Perl
Prerequisite: Perl | Hashes Set of key/value pair is called a Hash. Each key in a hash structure are unique and of type strings. The values associated with these keys are scalar. These values can either be a number, string or a reference. A Hash is declared using my keyword. Let us consider an example to understand the concept of sorting the hash.
6 min read
Perl | Hash Operations
Prerequisite: Perl Hashes, Perl Hash As most readers likely know, the hash stores data by using a mechanism called Hashing. In hashing, a key is used to determine a value or data. These keys must be unique and are then used as the index at which the data associated with the key is stored. This data does not have to be unique. It may be duplicated.
8 min read
Perl | Hash in Scalar and List Context
Prerequisite: Perl Hash Hash in Perl is a set of key/value pairs. Perl provides us the flexibility to assign the hash to a List type and a Scalar type, known as LIST Context and SCALAR Context respectively. Hash in LIST Context The assignment of a hash to a list type in Perl is accomplished by making a list with the keys and values as its elements.
5 min read
Perl | Useful Hash functions
A hash is a set of key-value pairs. Perl stores elements of a hash such that it searches for the values based on its keys. Perl provides various functions to perform operations on Hashes, such as to return values of the hash, to delete elements from a hash, etc. Example: #!/usr/bin/perl # Initializing hash %hash1 = ('Welcome' => 10, 'to' => 2
2 min read
Perl | Use of Hash bang or Shebang line
Practical Extraction and Reporting Language or Perl is an interpreter based language. Hash-bangs or shebangs are useful when we are executing Perl scripts on Unix-like systems such as Linux and Mac OSX. A Hashbang line is the first line of a Perl program and is a path to the Perl binary. It allows invoking the Perl scripts directly, without passing
3 min read
Perl - Creating a Hash from an Array
Hashing is the process of converting a given key into another value. A hash function is used to generate the new value (called hash) according to a mathematical algorithm. A Perl hash is defined by key-value pairs. Perl stores elements of a hash in such an optimal way that you can look up its values based on keys very fast. Like a scalar or an arra
4 min read
Perl | chomp() Function
The chomp() function in Perl is used to remove the last trailing newline from the input string. Syntax: chomp(String) Parameters: String : Input String whose trailing newline is to be removed Returns: the total number of trailing newlines removed from all its arguments Example 1: C/C++ Code #!/usr/bin/perl # Initialising a string $string = &quo
2 min read
Perl | Backtracking in Regular Expression
In Perl, a Regular expression(a.k.a regexes or regexps or REs) is a way of describing a set of strings without having to list all strings in your program or simply we can say that it is a sequence of characters that are used for pattern matching. In Perl, regular expressions have different uses: Firstly, they are used in conditionals to determine w
3 min read
Perl | Searching in a File using regex
Prerequisite: Perl | Regular Expressions Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to host language and are not the same as in PHP, Python, etc. Sometimes these are termed as "Perl 5 Compatible Regular Expressions". To use the Regex, Bindi
6 min read
Perl | Operators | Set - 1
Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Operators Can be categorized based upon their different functionality: Arithmetic OperatorsRelat
12 min read
Perl | lt operator
'lt' operator in Perl is one of the string comparison operators used to check for the equality of the two strings. It is used to check if the string to its left is stringwise less than the string to its right. Syntax: String1 lt String2 Returns: 1 if left argument is less than the right argument Example 1: #!/usr/local/bin/perl # Initializing Strin
1 min read
Perl | chop() Function
The chop() function in Perl is used to remove the last character from the input string. Syntax: chop(String) Parameters: String : It is the input string whose last characters are removed. Returns: the last removed character. Example 1: #!/usr/bin/perl # Initialising a string $string = "GfG is a computer science portal"; # Calling the chop
1 min read
Perl | rename() Function
rename() function in Perl renames the old name of a file to a new name as given by the user. Syntax: rename(old_file_path, new_file_path) Parameters: old_file_path: path of the old file along with its name new_file_path: path of the new file along with its name Returns 0 on failure and 1 on success Example: #!/usr/bin/perl -w # Calling the rename()
1 min read
Perl | Subroutines or Functions
A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In Perl, the terms function, subroutine, and method are the same but in s
2 min read
Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
Decision Making in programming is similar to decision making in real life. In programming, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance
6 min read
Perl | Loops (for, foreach, while, do...while, until, Nested loops)
Looping in programming languages is a feature which facilitates the execution of a set of instructions or functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Perl provides the different types of loop to handle the condition based situation in the program. The loops in Perl are : for Loop "for" loop
7 min read
Perl | Comparing Scalars
Prerequisite: Scalars in Perl Perl has two types of comparison operator sets. Just like other mathematical operators, instead of performing operations, these operators compare scalars. There are two types of sets of Perl comparison operators. One is for numeric scalar values and one is for string scalar values. Both the types are illustrated in bel
6 min read
Perl | String functions (length, lc, uc, index, rindex)
String in Perl is a sequence of character enclosed within some kinds of quotation marks. Perl string can contain UNICODE, ASCII and escape sequence characters. Perl provides the various function to manipulate the string like any other programming language. Some string functions of Perl are as follows: length() lc() uc() index() rindex() length(): T
4 min read
Perl | Arrays
In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Example: @number = (50, 70, 46); @names = ("Geeks", "For", "Geeks"); Array Creation: In Perl programming ever
6 min read
Perl | Data Types
Data types specify the type of data that a valid Perl variable can hold. Perl is a loosely typed language. There is no need to specify a type for the data while using in the Perl program. The Perl interpreter will choose the type based on the context of the data itself. There are 3 data types in Perl as follows: ScalarsArraysHashes(Associative Arra
3 min read
Perl | String Operators
Operators are the foundation of any programming language. Thus, the functionality of Perl programming language is incomplete without the use of operators. A user can define operators as symbols that help to perform specific mathematical and logical computations on operands. String are scalar variables and start with ($) sign in Perl. The String is
4 min read
Perl | Hashes
Set of key/value pair is called a Hash. Each key in a hash structure are unique and of type strings. The values associated with these keys are scalar. These values can either be a number, string or a reference. A Hash is declared using my keyword. The variable name is preceded by the dollar sign($)followed by key under curly braces and the value as
5 min read
Perl | Regular Expressions
Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“. To use the Regex, Binding operators like ‘=~‘(Regex Operator) and
2 min read
Perl | Regex Cheat Sheet
Regex or Regular Expressions are an important part of Perl Programming. It is used for searching the specified text pattern. In this, set of characters together form the search pattern. It is also known as regexp. When user learns regular expression then there might be a need for quick look of those concepts which he didn't use often. So to provide
6 min read
Introduction to Perl
Perl is a general-purpose, high level interpreted and dynamic programming language. It was developed by Larry Wall, in 1987. There is no official Full form of the Perl, but still, the most used expansion is "Practical Extraction and Reporting Language". Some of the programmers also refer Perl as the "Pathologically Eclectic Rubbish Lister" Or "Prac
9 min read
Perl | Regex Character Classes
Character classes are used to match the string of characters. These classes let the user match any range of characters, which user don’t know in advance. Set of characters that to be matched is always written between the square bracket []. A character class will always match exactly for one character. If match not found then the whole regex matchin
3 min read
Perl | Special Character Classes in Regular Expressions
There are many different character classes implemented in Perl and some of them used so frequently that a special sequence is created for them. The aim of creating a special sequence is to make the code more readable and shorter. The Special Character Classes in Perl are as follows: Digit \d[0-9]: The \d is used to match any digit character and its
4 min read
Perl | Subroutines or Functions | Set - 2
Prerequisite: Subroutines or Functions in Perl A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In this article we will di
4 min read
Perl | Operators | Set - 2
Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Some of the operators already discussed in Perl Operators Set - 1. Remaining operators will be d
7 min read
Article Tags :