Jun 22, 2008

Hash in Perl

Hashes are like named key value pairs.
Keys are always unique, Values can be anything.
It's best practice to use hashes, they are efficient.

 

use strict;
use warnings;
use Data::Dumper;

my %hash = (a => 10,
            e => 40,
            c => 30,
            d => 40,
            b => 20,
            a => 100);

#Print Keys
print "\n Only Keys:\n" . Dumper(keys %hash);

print "\n\n";
#Print Values
print "\n Only Values:\n" . Dumper(values %hash);


print "\n\n";
#Print Keys and Values
while ( my ($key, $value) = each %hash)
{
   print "$key => $value\n";
}

print "\n\n";



#Print Keys
print "\n Sorted Keys:\n" . Dumper(sort keys %hash);

print "\n\n";
#Print Values
print "\n Sorted Values:\n" . Dumper(sort values %hash);
  
Output:

 Only Keys:
$VAR1 = 'e';
$VAR2 = 'c';
$VAR3 = 'a';
$VAR4 = 'b';
$VAR5 = 'd';



 Only Values:
$VAR1 = 40;
$VAR2 = 30;
$VAR3 = 100;
$VAR4 = 20;
$VAR5 = 40;


e => 40
c => 30
a => 100
b => 20
d => 40



 Sorted Keys:
$VAR1 = 'a';
$VAR2 = 'b';
$VAR3 = 'c';
$VAR4 = 'd';
$VAR5 = 'e';



 Sorted Values:
$VAR1 = 100;
$VAR2 = 20;
$VAR3 = 30;
$VAR4 = 40;
$VAR5 = 40;
  


Please refer to other topics in Perl like :
How to read command line arguments in Perl
How to pass command line arguments to perl script
Loop through Directory and read the files in Perl
How to create excel report in Perl


Please refer to other topics on Unix like :
Unix Delete Duplicated Lines in a File
Unix Unique Lines in a File
Unix Grep Examples
Unix Cut Command Examples
Search a Directory in Unix
Unix For Loop
pushd & popd in Unix
Find Size of Directory
Word Count


Please refer to other topics on AWK like :
Awk Examples
Print First Two Columns of File
Print Last Two Columns of File


Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python


Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension


Please refer to other topics on File Concepts like :
Print File Content in Python
Print File in Reverse Order in Python


Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl


You might also wish to read other topics on Python like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton


No comments:

Post a Comment