- Perl Basics
- Perl Home
- Perl Basic Syntax
- Perl Data Types
- Perl Variables
- Perl Scalars
- Perl Arrays
- Perl Hashes
- Perl If-Else
- Perl Loops
- Perl Operators
- Perl References
- Perl Subroutines
- Perl Formats
- Perl Date & Time
- Perl File I/O
- Perl Advanced
- Perl Directory
- Perl Regular Expressions
- Perl Special Variables
- Perl Socket Programming
- Perl Send E-mail
- Perl Object Oriented
- Perl Error Handling
- Perl CGI Programming
- Perl Database
- Perl Packages & Modules
- Perl Process Management
- Perl Test
- Perl Online Test
- Give Online Test
- All Test List
Perl Hash
A hash in perl, is simply a set of key/value pairs. All the hash variables in perl, are preceded by percent (%) sign. You have to use hash variable name preceded by a dollar ($) sign to refer to a single element of a hash in perl, by the "key" associated with the value in the curly bracket.
Create Hash in Perl
You can create hash in two ways. In first way, you assign a value to a named key on one-by-one manner. Here is an example:
$names{'Deepak'} = 18; $names{'Rajat'} = 16; $names{'Ravi'} = 18;
Now, in second way, you use a list, converted by taking individual pairs from the list. The first element of the pair is used as key, and the second, is used as value. Here is an example:
%names = ('Deepak', 18, 'Rajat', 16, 'Ravi', 18);
For clarity and simplicity, you can use => as an alias for, to indicate the key/value pairs. Here is an example:
%names = ('Deepak' => 18, 'Rajat' => 16, 'Ravi' => 18);
Access Hash Elements in Perl
To access individual elements from a hash in perl, then you have to prefix the hash variable with a dollar ($) sign and then append the element key within a curly bracket after the variable's name. Here is an example:
#!/usr/bin/perl %names = ('Deepak' => 18, 'Rajat' => 16, 'Ravi' => 18); print("$names{'Deepak'}\n"); print("$names{'Rajat'}\n"); print("$names{'Ravi'}\n");
Here is the sample output of the above perl program:
18 16 18
Perl Hash Example
Here is an example program, illustrates hash in perl:
#!/usr/bin/perl %names = ('Deepak' => 18, 'Rajat' => 16, 'Ravi' => 18); print("\$names{'Deepak'} = $names{'Deepak'}\n"); print("\$names{'Rajat'} = $names{'Rajat'}\n"); print("\$names{'Ravi'} = $names{'Ravi'}\n");
Here is the sample output produced by the above perl program:
$names{'Deepak'} = 18 $names{'Rajat'} = 16 $names{'Ravi'} = 18
« Previous Tutorial Next Tutorial »