Perl Hashes

1) Hash stores a data in unsorted manner and has no intrinsic order.
2) A hash is a set of key/value pairs. A Hash's element can be accessed useing keys.
3) A hash variable must begin with a percent sign (%).
4) To refer to a single element of a hash, you will use the hash variable name preceded by a "$" sign and followed by the "key" associated with the value in curly brackets.
5) Hash keys must be unique. You cannot have more than one entry for the same name, and if you try to add a new entry with the same key as an existing entry, the old one will be over-written. Hash values meanwhile need not be unique.

1) Creating Hashes.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#!/usr/bin/perl
#Hashes can be defined in following ways
%data = (
 'Jerry' => 32, 
 'Adam' => 31, 
 'Chris' => 22
);

# or

$cities{'New York'} = 11;
$cities{'Washington'} = 22;
$cities{'London'} = 33;

2) Accessing Hash Elements.
1
2
3
4
5
6
7
#!/usr/bin/perl

%data = ('Jerry' => 32, 'Adam' => 31, 'Chris' => 22);

print "$data{'Jerry'} ";
print "$data{'Adam'} ";
print "$data{'Chris'} ";
Output: 32 31 22

3) Extracting Slices.
1
2
3
4
5
6
#!/usr/bin/perl

%data = ('Jerry' => 32, 'Adam' => 31, 'Chris' => 22);

@array = @data{Jerry, Chris};
print "Array : @array\n";
Output: Array : 32 22

4) Extracting key values.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#!/usr/bin/perl

%data = ('Jerry' => 32, 'Adam' => 31, 'Chris' => 22);

# Get a list of all of the keys from a hash by using keys function
@names = keys %data;

print "$names[0]\n";
print "$names[1]\n";
print "$names[2]\n";

# Get a list of all of the values from a hash by using values function
@age = values %data;

print "$age[0]\n";
print "$age[1]\n";
print "$age[2]\n";

5) Checking for existence using exist() function.
1
2
3
4
5
6
7
8
9
#!/usr/bin/perl

%data = ('Jerry' => 32, 'Adam' => 31, 'Chris' => 22);

if( exists($data{'Chris'} ) ) {
   print "Chris is $data{'Chris'} years old\n";
} else {
   print "I don't know age of Chris\n";
}

6) Getting Hash size using keys or values.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#!/usr/bin/perl

%data = ('Jerry' => 32, 'Adam' => 31, 'Chris' => 22);

@keys = keys %data;
$size = @keys;
print "Hash size:  is $size\n";

@values = values %data;
$size = @values;
print "Hash size:  is $size\n";

7) Add and remove elements in hashes.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/perl

%data = ('Jerry' => 32, 'Adam' => 31, 'Chris' => 22);

#Hash Size
@keys = keys %data;
$size = @keys;
print "1) Hash size:  is $size\n";

#Add Element in hash
$data{'Oleg'} = 55;
@keys = keys %data;
$size = @keys;
print "2) Added Element, now Hash size:  is $size\n";

# Delete the same element from the hash;
delete $data{'Adam'};
@keys = keys %data;
$size = @keys;
print "3) Removed Element, now Hash size:  is $size\n";
Output:
1) Hash size:  is 3
2) Added Element, now Hash size:  is 4
3) Removed Element, now Hash size:  is 3



<-- Previous || Next -->

1 comment: