Perl Tutorial - Practical Extraction and Reporting Language (Perl)
Please leave a remark at the bottom of each page with your useful suggestion.
Table of Contents
- Perl Introduction
- Perl Program Startup
- Perl Regular Expressions
- Perl Array Program
- Perl Basic Program
- Perl Subroutine / Function Program
- Perl XML Program
- Perl String Program
- Perl Statement Program
- Perl Network Program
- Perl Hash Program
- Perl File Handling Program
- Perl Data Type Program
- Perl Database Program
- Perl Class Program
- Perl CGI Program
- Perl GUI Program
- Perl Report Program
Perl Hash Program
Accessing Elements
# Assigning keys and values to a hash
%department = ("Eng" => "Engineering",
"M" => "Math",
"S" => "Science",
"CS" => "Computer Science",
"Ed" => "Education",
);
$department = $department{'M'}; # Either single or double quotes# ok for the keys
$school = $department{'Ed'};
print "$department\n" ;
print "$school.\n";
print qq/$department{'CS'}.\n/;
print qq/testing:\n/;
print %department, "\n";
Adding elements to a hash
%hash = ( width => '300', height => '150' );
$hash{ 'color' } = 'blue';
print "\$hash{ 'width' } = $hash{ 'width' }\n";
print "\$hash{ 'height' } = $hash{ 'height' }\n";
print "\$hash{ 'color' } = $hash{ 'color' }\n\n";
An associative array, called a hash, is an unordered list of key/value pairs, indexed by strings.
#The name of the hash is preceded by a "%" symbol.
%employee = (
"Name" => "AA",
"Phone" => "(999) 555-1234",
"Position" => "CEO"
);
print $employee{"Name"};
$employee{"SSN"}="999-333-2345";
Anonymous Hash References
#!/usr/local/bin/perl -w
my $hashRef = {'Name' => 'Tom', 'Age' => 3, 'Height' => '10 cm'};
print $hashRef->{'Name'} . "\n";
print $hashRef->{'Age'} . "\n";
print $hashRef->{'Height'} . "\n";
Associative arrays are indexed by string values.
#!/usr/local/bin/perl -w
my %cities = ("Toronto" => "East", "Calgary" => "Central", "Vancouver" => 'West');
for $key (keys %cities)
{
print "Key: $key Value: $cities{$key} \n";
}
Associative arrays or hashes
The regular arrays allow you to access elements by their index numbers, starting at 0.
Associative arrays allow you to access elements by key names.
An associative array or hash holds a set of key/value pairs.
A key name is any arbitrary scalar value.
Perl uses a percent sign (%) to indicate that a variable is a hash.
Any value in a hash can be accessed through its key name with the following syntax:
The dollar sign ($) means that the value held in the hash under a given key name is a scalar value.
$hash{keyname}
Building a Price List
#!/usr/local/bin/perl
%inventory = (A=>45_000.00,b=>120.00,C=>450_000.00,d=>40.00);
open (INV, ">price.list");
foreach $item (sort keys %inventory){
print INV join(":", ($item, $inventory{"$item"})), "\n";
}
close INV;
Check key existance after using 'delete' operator
$hash{fruit} = apple;
$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
delete($hash{'fruit'});
if (exists($hash{"fruit"})) {
print "Key exists.";
} else {
print "Key does not exist.";
}
Converting a hash into an array by simple assignment
#!/usr/bin/perl -w
# Convert hash to array
$hash{"Name"} = "G ";
$hash{"Address"} = "1";
$hash{"City"} = "W";
@array = %hash;
Create hash from scalar variable
$hash2{A} = F;
$hash2{B} = E;
$hash2{'C'} = D;
Create hash with => operator
%hash = (
fruit => apple,
sandwich => hamburger,
drink => bubbly,
);
print "$hash{fruit}\n";
Create hash without using the quotation marks
%hash = (
fruit , apple,
sandwich , hamburger,
drink , bubbly,
);
print "$hash{fruit}\n";
Create hash with qw
%hash = qw(
fruit apple
sandwich hamburger
drink bubbly
);
print "$hash{'fruit'}\n";
Creating and accessing hash elements
%hash = ( width => '300', height => '150' );
print "\$hash{ 'width' } = $hash{ 'width' }\n";
print "\$hash{ 'height' } = $hash{ 'height' }\n\n";
Delete an entry in hash
#!/usr/bin/perl -w
use strict;
my %where = (
G => "Dallas",
L => "Exeter",
I => "Reading",
S => "Oregon"
);
delete $where{L};
print "Lucy lives in $where{L}\n";
Delete from hash
#!C:/Perl/Bin
%animals = (H=> 'h', S=> 's', G=> 'g');
print "$animals{'S'} \n\n";
foreach $creature(keys %animals)
{
print "$creature \n";
}
print "\n\ndeleting...\n\n";
delete($animals{Shark});
foreach $creature(keys %animals)
{
print "$creature \n";
}
print "\n\n'emptying' the hash ...\n\n";
%animals=();
print "Displaying empty hash ...\n\n";
foreach $creature(keys %animals)
{
print "$creature \n";
}
Delete the element with key 'Joe' from %hash
%hash = ( Karl => 2,
Joe => 3,
Shawn => 0,
Paul => 1,
Bill => undef );
# obtain the list of hashKeys and display each key-value pair
@hashKeys = keys( %hash );
for ( $i = 0; $i < @hashKeys; ++$i ) {
print "$hashKeys[ $i ] => $hash{ $hashKeys[ $i ] }\n";
}
delete( $hash{ 'Joe' } );
Demonstrating hash slices.
%romanNumerals = ( one => 'I',
two => 'II',
three => 'III',
four => 'IV',
five => 'V',
six => 'VI',
seven => 'VII',
eight => 'VIII',
nine => 'IX',
ten => 'X' );
print "The Roman numerals for three, five and eight are: ",
"@romanNumerals{ 'three', 'five', 'eight' }\n";
Dereferencing hash
#!/usr/bin/perl
use warnings;
use strict;
my @array = (1, 2, 3, 4, 5);
my $array_r = \@array;
print "This is our dereferenced array: @$array_r\n";
for (@$array_r) {
print "An element: $_\n";
}
print "The highest element is number $#$array_r\n";
print "This is what our reference looks like: $array_r\n";
Determine if a particular key exists
%hash = ( Karl => 2,
Joe => 3,
Shawn => 0,
Paul => 1,
Bill => undef );
# obtain the list of hashKeys and display each key-value pair
@hashKeys = keys( %hash );
for ( $i = 0; $i < @hashKeys; ++$i ) {
print "$hashKeys[ $i ] => $hash{ $hashKeys[ $i ] }\n";
}
delete( $hash{ 'Joe' } );
while ( $key = pop( @hashKeys ) ) {
print "\n";
# determine if a particular key exists
if ( exists( $hash{ $key } ) ) {
print "$key exists in the hash.\n";
}
else {
print "$key doesn't exist in the hash.\n";
}
}
Determine if the value for the key is defined
%hash = ( Karl => 2,
Joe => 3,
Shawn => 0,
Paul => 1,
Bill => undef );
# obtain the list of hashKeys and display each key-value pair
@hashKeys = keys( %hash );
for ( $i = 0; $i < @hashKeys; ++$i ) {
print "$hashKeys[ $i ] => $hash{ $hashKeys[ $i ] }\n";
}
delete( $hash{ 'Joe' } );
while ( $key = pop( @hashKeys ) ) {
print "\n";
# determine if the value for the key is defined
if ( defined( $hash{ $key } ) ) {
print "$key is defined as $hash{ $key }.\n";
}
else {
print "$key is undefined.\n";
}
}
Determine if the value for the key is true or false
%hash = ( Karl => 2,
Joe => 3,
Shawn => 0,
Paul => 1,
Bill => undef );
# obtain the list of hashKeys and display each key-value pair
@hashKeys = keys( %hash );
for ( $i = 0; $i < @hashKeys; ++$i ) {
print "$hashKeys[ $i ] => $hash{ $hashKeys[ $i ] }\n";
}
delete( $hash{ 'Joe' } );
while ( $key = pop( @hashKeys ) ) {
print "\n";
# determine if the value for the key is true or false
if ( $hash{ $key } ) {
print "$key is true.\n";
}
else {
print "$key is false.\n";
}
}
Display a hash with print
%hash = ( width => '300', height => '150' );
$hash{ 'color' } = 'blue';
print "%hash\n";
print %hash, "\n";
Display the list of values
%presidents = ( George => "Washington",
Abe => "Lincoln",
Thomas => "Jefferson",
Harry => "Truman" );
# obtain the list of keys and display each key-value pair
@keys = keys( %presidents );
@values = values( %presidents );
print "\nThe values of the hash are:\n@values\n\n";
Dump the hash
#!/usr/bin/perl
use warnings;
use Data::Dumper;
my $hashref = {a=>1, b=>2, h=>{c=>3, d=>4}, e=>[6, 7, 8]};
print Dumper($hashref);
Each function:
#!/usr/local/bin/perl -w
my %cities = ("Toronto" => "East", "Calgary" => "Central", "Vancouver" => 'West');
while ( ($key, $value) = each %cities )
{
print "Key: $key Value: $value \n";
}
each function returns both key and value in a hash
$hash{fruit} = orange;
$hash{sandwich} = club;
$hash{drink} = lemonade;
while (($key, $value) = each %hash ) {
print "$key: $value\n";
}
Empty hash
%hash = ();
print %hash;
print "\n";
$hash{fruit} = apple;
$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
print %hash;
Get hash value by using the hash reference
#!/usr/bin/perl
use strict;
use warnings;
my %hash = ( A => "AA",
B => "BB",
C => "CC",
D => "DD",
E => "EE" );
my $hashReference = \%hash;
print( "\$\$hashReference{ A } = $$hashReference{ A }\n" );
Get key value pair through hash reference
%hash = (that => this);
$hashreference = \%hash;
print "$$hashreference{that}\n";
Hard References-Pointers
my $arrayptr=\@array; # creates a pointer to an array
my $scalarptr=\$scalar; # creates a pointer to a scalar
my $hashptr=\%assoc_array; # creates a pointer to a hash
my $funcptr=\&subroutine; # creates a pointer to a subroutine
Hash (Associative Array) Functions: The keys function returns, in random order, the keys of a hash.
#Format:
#keys(ASSOC_ARRAY)
#keys ASSOC_ARRAY
# The keys function returns the keys of a hash
%weekday= ( '1'=>'Monday',
'2'=>'Tuesday',
'3'=>'Wednesday',
'4'=>'Thursday',
'5'=>'Friday',
'6'=>'Saturday',
'7'=>'Sunday',
);
foreach $key ( keys(%weekday) ){print "$key ";}
print "\n";
foreach $key ( sort keys(%weekday) ){print $key ;}
print "\n";
Hashes: An associative array
% pet = ( "Name" => "Sneaky",
"Type" => "Cat",
"Owner" => "Carol",
"Color" => "yellow",
);
Hashes Assignment in action
%seasons=("A" => "Spring",
"B" => "Summer",
"C" => "Fall",
"D" => "Winter",
);
%days=("Mon" => "Monday",
"Tue" => "Tuesday",
"Wed" => undef,
);
$days{"Wed"}="Wednesday";
$days{5}="Friday";
Hash example
#!/usr/bin/perl
use warnings;
use strict;
my %hash = (
1 => "January", 2 => "February", 3 => "March", 4 => "April",
5 => "May", 6 => "June", 7 => "July", 8 => "August",
9 => "September", 10 => "October", 11 => "November", 12 => "December"
);
my $href = \%hash;
for (keys %$href) {
print "Key: ", $_, " ";
print "Hash: ",$hash{$_}, " ";
print "Ref: ",$$href{$_}, " ";
print "\n";
}
Hash hash overwrites
#!/usr/bin/perl
use strict;
use warnings;
my %default_animals = (Cat => 'Tom', Mouse => 'Jerry');
my %input_animals = (Cat => 'Ginger', Mouse => 'Jerry');
my %animals = (%default_animals, %input_animals);
print "$animals{Cat}\n"; # prints 'Ginger'
Hash Key and Value Retrieval
#!/usr/local/bin/perl
%priceList = (
"A"=>2.2,
"B"=>3.1,
"C"=>4.0,
"D"=>5.1,
"E"=>6.7,
"F"=>7.6,
);
@keyList = keys %priceList;
print "@keyList";
foreach $index (keys(%myPriceList)){
print "The price of item $key is $priceList{$index}\n";
}
print "\n\n";
foreach $key (@keyList){
print "The price of item $key is $priceList{$key}\n";
}
@valueList = values %priceList;
print "\n";
print "@valueList";
Hash Key-Value Pair Retrieval
$separator = "=" x 80;
while (($key, $value) = each %ENV){
print "$key \t\t==> $value\n";
}
print "$separator\n";
foreach $key (sort keys %ENV){
print qq|$key \t\t==> $ENV{"$key"}\n|;
}
Hash List Assignment
#!/usr/local/bin/perl
print "\n\n";
%priceList = (
"A"=>2.92,
"B"=>3.31,
"C"=>1.00,
"D"=>1.01,
"E"=>2.87,
"F"=>2.56,
);
printAA(%priceList);
print "$priceList{'A'}\n";
%priceList = (
1=>28.92,
2=>36.31,
3=>124.00,
4=>178.01,
5=>205.87,
6=>24.56,
);
print "Or like this $priceList{1} \n\n";
printAA(%priceList);
sub printAA {
my %myPriceList = @_;
foreach $key (keys(%myPriceList)){
print "$key is $priceList{$key}\n";
}
print "\n\n";
}
Hash map creation
#!C:/Perl/Bin
%animals = (H=> 'h', S=> 's', G=> 'g');
print "$animals{'Shark'} \n\n";
foreach $creature(keys %animals)
{
print "$creature \n";
}
Hash of Hashes
#!/bin/perl
my $hashref = {
Math => { # key
"A" => 100,
"H" => 95, # values
},
Science => { # key
"S" => 78,
"L" => 100, # values
},
};
print "$hashref->{'Math'}->{'A'}.\n";
$hashref->{'Science'}->{'L'}=90;
print "$hashref->{'Science'}->{'L'}.\n";
print %{$hashref->{'Math'}}, "\n";
foreach $key (keys %{$hashref}){
print "Outer key: $key \n";
while(($nkey,$nvalue)=each(%{$hashref->{$key}})){
printf "\tInner key: %-5s -- Value: %-8s\n",$nkey,$nvalue;
}
}
Hash of Hashes with Lists of Values
my $hashptr = { "Teacher"=>{"Subjects"=>[ qw(Science English)]},};
print $hashptr->{"Teacher"}->{"Subjects"}->[0],"\n";
print "@{$hashptr->{'Musician'}->{'Instruments'}}\n";
Hash of list
%hash_of_lists = (
List_1 => [1, 2, 3],
List_2 => ["Red", "Yellow", "Blue"],
);
print "$hash_of_lists{List_1}[1]", "\n";
Hash References
#!/usr/bin/perl
use warnings;
use strict;
my %hash = (
1 => "January", 2 => "February", 3 => "March", 4 => "April",
5 => "May", 6 => "June", 7 => "July", 8 => "August",
9 => "September", 10 => "October", 11 => "November", 12 => "December"
);
my $href = \%hash;
for (keys %{$href}) {
print "Key: ", $_, "\t";
print "Hash: ",$hash{$_}, "\t";
print "Ref: ",${$href}{$_}, "\n";
}
Hash setting and getting
$hash{name} = "AAA";
print $hash{name};
Hash Slices
%officer= ("NAME"=> "A",
"SSN" => "123456",
"DOB" => "05/19/2009"
);
@info=qw(Tom Jack 50000);
@officer{'BRANCH', 'TITLE', 'SALARY'}=@info;
@sliceinfo = @officer{'NAME','BRANCH','TITLE'};
print "new value: @sliceinfo\n\n";
foreach $key ('NAME', 'SSN', 'DOB', 'BRANCH', 'TITLE', 'SALARY'){
printf "Key: %-10sValue: %-15s\n", $key, $officer{$key};
}
Hash Value Sorting
#!/usr/local/bin/perl
%Inventory = (a=>45_000.00,b=>120.00,c=> 450_000.00,d=>40.00);
$sortHash = \%Inventory;
@keyList = sort sortHashByValue keys %Inventory;
foreach $key (@keyList){
print "key==>$key, \tprice==>$Inventory{$key}\n";
}
sub sortHashByValue(){
$$sortHash{"$a"} <=> $$sortHash{"$b"};
}
If an entry exist
#!/usr/bin/perl -w
use strict;
my @names = qw(
A E I
B F J
C G K
D H L
);
my %count;
foreach (@names) {
if (exists $count{$_}) {
$count{$_}++;
} else {
$count{$_} = 1;
}
}
foreach (keys %count) {
print "$_ \toccurs $count{$_} time(s)\n";
}
Is a key defined in a hash
$hash{fruit} = apple;
$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
if (defined($hash{'vegetable'})) {
print "Element is defined.";
} else {
print "Element is not defined.";
}
Is a key in a hash
$hash{fruit} = apple;
$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
if (exists($hash{'vegetable'})) {
print "Key is in the hash.";
} else {
print "Key is not in the hash.";
}
Is hash key defined and existed
#!/usr/bin/perl
use strict;
use warnings;
my %hash = ('Key1' => 'Value1', 'Key2' => 'Value2');
my $key = 'Key1';
if (exists $hash{$key}) {
if (defined $hash{$key}) {
print "$key exists and is defined as $hash{$key} \n";
} else {
print "$key exists but is not defined \n";
}
} else {
print "$key does not exist\n";
}
Iterate hash
#!/usr/bin/perl
use strict;
use warnings;
my %hash = ('Key1' => 'Value1', 'Key2' => 'Value2');
print "$_ => $hash{$_} \n" foreach keys %hash;
foreach (sort values %hash) {
print "Value: $_ \n";
}
Join hash key
$hash2{A} = F;
$hash2{B} = E;
$hash2{'C'} = D;
print join(" ", %hash);
Keys function is used to get all keys in a hash
#!/usr/bin/perl -w
use strict;
my %where = (
G => "Dallas",
L => "Exeter",
I => "Reading",
S => "Oregon"
);
foreach (keys %where) {
print "$_ lives in $where{$_}\n";
}
List context and hash context
#!/usr/bin/perl -w
use strict;
my %person = (
name => 'Joe',
age => 13,
phone => '555-1212',
city => 'Chicago'
);
my @data = %person;
print "list context: ", join("|", @data), "\n";
print "another way: ", %person, "\n";
List of hash
#!/usr/bin/perl
use warnings;
use strict;
my (@list_of_hashes, %hash_of_lists, %mixed_bag, $my_object);
my @my_list = (1,2,3,4,5);
@list_of_hashes = (
{ Monday=>1, Tuesday=>2, Wednesday=>3, Thursday=>4, Friday=>5 },
{ Red=>0xff0000, Green=>0x00ff00, Blue=>0x0000ff },
);
print "$list_of_hashes[0]{Tuesday}.", "\n";
Lists the contents of an associative array using the values function:
#!/usr/local/bin/perl -w
my %cities = ("Toronto" => "East", "Calgary" => "Central", "Vancouver" => 'West');
for $value (values %cities)
{
print "Value: $value \n";
}
Lock value and keys
#!/usr/bin/perl
use strict;
use warnings;
use Hash::Util qw(lock_keys unlock_keys lock_hash unlock_hash lock_value unlock_value);
my %hash1=(one =>'first', two=>'second', three=>'third');
lock_keys(%hash1);
unlock_keys(%hash1);
my %hash2;
lock_keys(%hash2,'one','two','six');
lock_value(%hash2,'one');
lock_value(%hash2,'two');
unlock_value(%hash2,'two');
Looping Over A Hash
#!/usr/bin/perl
use warnings;
use strict;
my %where=(
G => "g",
L => "l",
I => "i",
S => "s"
);
for (keys %where) {
print "$_ lives in $where{$_}\n";
}
Loop through an associative array
while(<>) {
chop;
($Header, $Value) = split(/:/,$_,2);
$Value =~ s/^\s+//; # remove trailing whitespace
$Heading{$Header} = $Value;
}
foreach $Head (sort keys %Heading) {
print "$Head --> $Heading{$Head}\n";
}
Loop through an associative array While loop
while(<>) {
chop;
($Header, $Value) = split(/:/,$_,2);
$Value =~ s/^\s+//; # remove trailing whitespace
$Heading{$Header} = $Value;
}
while ( ($Head,$Val) = each %Heading) {
print "$Head --> $Val\n";
}
Merge two hash variable
$h1{fruit} = apple;
$h1{sandwich} = hamburger;
$h1{drink} = bubbly;
$h2{cake} = chocolate;
$h2{pie} = blueberry;
$h2{'ice cream'} = pecan;
%h3 = (%h1, %h2);
print $h3{'ice cream'};
Mix scalar, list and hash
%mixed_bag = (
Scalar1 => 3,
Scalar2 => "A",
List1 => [1, 2, 3],
Hash1 => { A => 'a', C => 'c' },
List2 => ['A','B', ['C','D'], 'E', 'F'],
Scalar3 => $my_object,
Hash2 => { Time => [ gmtime ],Date => scalar(gmtime),
},
List3 => @my_list[0..2],
);
print $mixed_bag{List2}[2][1];
Nested hashes
%students=( "Math" => { "A" => 100, "B" => 95 },
"Science" => { "C" => 85, "D" => 76 }
);
print qq/$students{Math}->{Joan}.\n/;
print qq/$students{Science}->{Bill}.\n/;
Numerically Sort a Hash by Values in Ascending Order
sub asc_sort_salary {
$salary{$a} <=> $salary{$b};
}
%salary = (
"P" => 10,
"S" => 12,
"C" => 5,
"S" => 6,
"L" => 11,
"D" => 8,
);
foreach $key (sort asc_sort_salary(keys(%salary))) {
printf "\t% -20s%5d\n", $key, $salary{$key};
}
Numerically Sort a Hash by Values in Descending Order
sub desc_sort_salary {
$salary{$b} <=> $salary{$a}; # Reverse $a and $b
}
%salary = (
"P" => 10,
"S" => 12,
"C" => 5,
"S" => 6,
"L" => 11,
"D" => 8,
);
foreach $key (sort desc_sort_salary(keys(%salary))) {
printf "\t% -20s%5d\n", $key, $salary{$key};
}
Obtain the list of hashKeys and display each key-value pair
%hash = ( Karl => 1,
Joe => 3,
Shawn => 0,
Paul => 2,
Bill => undef );
@hashKeys = keys( %hash );
for ( $i = 0; $i < @hashKeys; ++$i ) {
print "$hashKeys[ $i ] => $hash{ $hashKeys[ $i ] }\n";
}
Obtain the list of keys and display each key-value pair
%presidents = ( George => "A",
Abe => "B",
Thomas => "C",
Harry => "D" );
@keys = keys( %presidents );
while ( $key = pop( @keys ) ) {
print "$key => $presidents{ $key }\n";
}
Ordered hash
#!/usr/bin/perl
use strict;
use warnings;
use Tie::IxHash;
my %hash;
tie %hash, 'Tie::IxHash';
%hash = (one => 1, two => 2, three => 3);
print join(",",keys(%hash)),"\n";
Output nested hash
#!/usr/bin/perl
use warnings;
use strict;
my %outer = (A=> {a1=>1, a2=>2, a3=>3},
B=> {b1=>4, b2=>5, b3=>6},
C=> {c1=>7,c2=>8, c3=>9});
foreach my $outer_key (keys %outer) {
print "$outer_key => \n";
foreach (keys %{$outer{$outer_key}} ) {
print"\t$_ => $outer{$outer_key}{$_} \n";
}
print "\n";
}
Pass key and get value
%hash = ();
$hash{fruit} = apple;
$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
print $hash{sandwich};
Print mixed structure
#!/usr/bin/perl
use warnings;
use strict;
my $mixed = [
'scalar', ['a', 'B', ['c', 'd'], 'e'],
{And=>{'A'=>'A'}}, \'a scalar ref'
];
print_structure($mixed);
sub print_structure {
my ($data) = @_;
foreach (ref $data) {
/^$/ and print($data,"\n"), next;
/^SCALAR/ and print('-> ', $$data, "\n"), next;
/^HASH/ and do {
print "\n";
foreach my $key (keys %{$data}) {
print "$key => ";
print_structure ($data->{$key});
}
next;
};
/^ARRAY/ and do {
print "\n";
for my $elc (0..$#{$data}) {
print "[$elc] : ";
print_structure ($data->[$elc]);
}
next;
};
print "?$data?";
}
}
Reference a non-exist hash value
#!/usr/bin/perl -w
use strict;
my %where = (
G => "Dallas",
L => "Exeter",
I => "Reading",
S => "Oregon"
);
delete $where{L};
print "Lucy lives in $where{L}\n";
Reference for hash
#!/bin/perl
@toys = qw( A B C );
$num = @toys;
%games=("A" => "a",
"B" => "B",
"C" => "C",
);
$ref1 = \$num;
$ref2 = \@toys;
$ref3 = \%games;
print "$$ref1.\n"; # dereference pointers
print "",join(",",@$ref2), ".\n";
print "$ref2->[0].\n";
print "$ref2->[2].\n";
while(($key,$value)=each(%$ref3)){
print "$key => $value\n";
}
print "$ref3->{'C'}\n";
Reference one value in hash by its key in print statement
$hash{'fruit'} = 'apple';
print "$hash{'fruit'}\n";
Reverse a hash
#!/usr/bin/perl -w
use strict;
my %where = (
A => "AA",
B => "BB",
C => "CC",
D => "DD"
);
my %who = reverse %where;
foreach (keys %who) {
print "in $_ lives $who{$_}\n";
}
Reverse a hash: use key as the value, and value as the key
$hash{fruit} = apple;
$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
%reversed = reverse %hash;
foreach $key (sort keys %reversed) {
print "$key => $reversed{$key}\n";
}
Reverse the hash and use function each to get each pair
%presidents = ( George => "A",
Abe => "B",
Thomas => "C",
Harry => "D" );
@keys = keys( %presidents );
@values = values( %presidents );
print "%presidents with its keys and values reversed\n";
%hash = reverse( %presidents );
while ( ( $key, $value ) = each( %presidents ) ) {
print "$key => $value\n";
}
Reverse the key and value
#!/usr/bin/perl
use strict;
use warnings;
my %hash = ('Key1' => 'Value1', 'Key2' => 'Value2');
print "$hash{Key1}\n"; # print 'Value1'
foreach (keys %hash) {
$hash{$hash{$_}} = $_;
delete $hash{$_};
}
print "$hash{Value1}\n"; # print 'Key1'
Setting values into a hash named %hash
#!/usr/bin/perl -w
$hash{"Name"} = "G ";
$hash{23} = 365;
$hash{123.45} = "Hello world";
$key = 123.45;
print "Element 123.45: $hash{$key}\n";
$key = "Name";
print "Element Name: $hash{$key}\n";
Sort Hash by Keys in Reverse Order
%salary = ("P" => 10,
"S" => 12,
"C" => 5,
"S" => 6,
"L" => 11,
"D" => 8,
);
foreach $key (reverse sort(keys %salary)) {
printf "\t% -20s%5d\n", $key, $salary{$key};
}
Sort Hash by Keys Numerically
sub desc_sort_subject {
$b <=> $a; # Numeric sort descending
}
sub asc_sort_subject{
$a <=> $b; # Numeric sort ascending
}
%courses = (
"101" => "I",
"221" => "L",
"300" => "A",
"102" => "P",
"103" => "P",
"200" => "L",
);
foreach $key (sort asc_sort_subject(keys(%courses))) {
printf "\t%-5d%s\n", $key, $courses{"$key"};
}
foreach $key (sort desc_sort_subject(keys(%courses))) {
printf "\t%-5d%s\n", $key, $courses{"$key"};
}
Sorting a Hash
%salary = (
"P" => 10,
"S" => 12,
"C" => 5,
"S" => 6,
"L" => 11,
"D" => 8,
);
foreach $key( sort(keys %salary)) {
printf "\t% -20s%5d\n", $key, $salary{$key};
}
Sort keys in a hash
$hash{fruit} = apple;
$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
foreach $key (sort keys %hash) {
print "$key => $hash{$key}\n";
}
Sort values in a hash
$hash{fruit} = apple;
$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
foreach $value (sort values %hash) {
print "$value\n";
}
Store color value in a hash
#!/usr/bin/perl -w
use strict;
my %colors = (
red => '#FF0000',
green => '#00FF00',
blue => '#0000FF',
white => '#FFFFFF',
black => '#000000',
purple => '#520063'
);
print "Red is: $colors{red}\n";
print "Blue is: $colors{blue}\n";
print "Purple is: $colors{purple}\n";
The delete Function
Format: delete $ASSOC_ARRAY{KEY}
#!/usr/bin/perl
%employees=(
"Tester" => "Joe",
"Coder" => "Teddy",
"Clerk" => "Tom",
);
$layoff=delete $employees{"Colder"};
print "We had to let $layoff go.\n";
while(($key, $value)=each(%employees)){
print "$key: $value\n";
}
The delete operator removes a key/value pair from an associative array.
#!/usr/bin/perl -w
# Deleting hash elements.
$hash{"Name"} = "A";
$hash{"Address"} = "B";
$hash{"City"} = "C";
print ' Print keys before deletion.';
@key_names = keys(%hash);
print "Key names are: @key_names\n\n";
print 'Delete item and print.';
delete $hash{"Address"};
print ' Print keys after .';
@key_names = keys(%hash);
print "Key names now: @key_names\n\n";
The each function returns, in random order, a two-element array: the key and the value of a hash.
#Format: each(ASSOC_ARRAY)
#! /usr/bin/perl
# The each function retrieves both keys and values from a hash
%weekday=(
'Mon' => 'Monday',
'Tue' => 'Tuesday',
'Wed' => 'Wednesday',
'Thu' => 'Thursday',
'Fri' => 'Friday',
'Sat' => 'Saturday',
'Sun' => 'Sunday',
);
while(($key,$value)=each(%weekday)){
print "$key = $value\n";
}
The exists function returns true if a hash key (or array index) has been defined, and false if not.
#Format: exists $ASSOC_ARRAY{KEY}
#!/usr/bin/perl
%employees=("Tester" => "Joe",
"Coder" => "Teddy",
"Clerk" => "Tom",
);
print "exists.\n" if exists $employees{"Tester"};
print "The Clerk exists.\n" if exists $employees{"Clerk"};
print "The Boss does not exist.\n" if not exists $employees{"Boss"};
The keys operator returns a list of all the key names within a hash.
#!/usr/bin/perl -w
# Associative array or hash keys.
$hash{"Name"} = "G ";
$hash{"Address"} = "1 Penn.";
$hash{"City"} = "W";
@key_names = keys(%hash);
print "Key names are: @key_names\n\n";
# Now, access each element from the list.
foreach $key (@key_names) {
print "$key holds $hash{$key}\n";
}
The values function returns, in random order, an array consisting of all the values of a hash.
#Format:
#values(ASSOC_ARRAY)
#values ASSOC_ARRAY
# The values function returns the values in a hash
%weekday= ( '1'=>'Monday',
'2'=>'Tuesday',
'3'=>'Wednesday',
'4'=>'Thursday',
'5'=>'Friday',
'6'=>'Saturday',
'7'=>'Sunday',
);
foreach $value ( values(%weekday)){print "$value";}
print "\n";
To tell if a given key name exists in a hash, you can use the exists operator.
#if ( exists($hash{$key} ) ) {
# # ..
#}
$hash{"Name"} = "A";
$hash{"Address"} = "B";
$hash{"City"} = "C";
if ( exists($hash{"City"} ) ) {
print 'exists';
}
Use hash as an array
$hash{fruit} = apple;
$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
print "@{[%hash]}\n";
Using array as the hash value
$string = "Here's a string.";
@array = (1, 2, 3);
%hash = ('fruit' => 'apples', 'vegetable' => 'corn');
sub printem
{
print shift;
}
$complex = {
string => $string,
number => 3.1415926,
array => [@array],
hash => {%hash},
arrayreference => \@array,
hashreference => \%hash,
sub => \&printem,
anonymoussub => sub {print shift;},
handle => \*STDOUT,
};
print $complex->{string}, "\n";
print $complex->{number}, "\n";
print $complex->{array}[0], "\n";
print $complex->{hash}{fruit}, "\n";
print ${$complex->{arrayreference}}[0], "\n";
print ${$complex->{hashreference}}{"fruit"}, "\n";
$complex->{sub}->("Subroutine call.\n");
$complex->{anonymoussub}->("Anonymous subroutine call.\n");
print {$complex->{handle}} "Text printed to a handle.", "\n";
Using customized function to sort keys in a hash
$hash{fruit} = apple;
$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
foreach $key (sort {myfunction($a, $b)} keys %hash) {
print "$key => $hash{$key}\n";
}
sub myfunction
{
return (shift(@_) cmp shift(@_));
}
Using each function with hash reference
$hashref = {
fruit => apple,
sandwich => hamburger,
drink => bubbly,
};
while(($key, $value) = each(%$hashref)) {
print "$key => $value\n";
}
Using each to get key and value pair from hash
$hash2{A} = F;
$hash2{B} = E;
$hash2{'C'} = D;
while(($key, $value) = each(%hash)) {
print "$key => $value\n";
}
Using foreach loops with hashes
@opinions = qw( A b c d e f g h jk r e r t r e e e e e ww );
foreach ( @opinions ) {
++$hash{ $_ };
}
# display sorted by frequency in descending order
print "\nWord\tFrequency\n";
print "----\t---------\n";
foreach ( sort { $hash{ $b } <=> $hash{ $a } } keys( %hash ) ) {
print "$_\t", "*" x $hash{ $_ }, "\n";
}
Using -> opertor with hash reference variable
#!/usr/bin/perl
use strict;
use warnings;
my @array = qw( A B C D E );
my %hash = ( A => "AA",
B => "BB",
C => "CC",
D => "DD",
E => "EE" );
my $arrayReference = \@array;
my $hashReference = \%hash;
sub returnReference
{
return \@array;
}
print ( "\$hashReference->{ duck } = $hashReference->{ duck }\n\n" );
Using hash as the hash value
$string = "Here's a string.";
@array = (1, 2, 3);
%hash = ('fruit' => 'apples', 'vegetable' => 'corn');
sub printem
{
print shift;
}
$complex = {
string => $string,
number => 3.1415926,
array => [@array],
hash => {%hash},
arrayreference => \@array,
hashreference => \%hash,
sub => \&printem,
anonymoussub => sub {print shift;},
handle => \*STDOUT,
};
print $complex->{string}, "\n";
print $complex->{number}, "\n";
print $complex->{array}[0], "\n";
print $complex->{hash}{fruit}, "\n";
print ${$complex->{arrayreference}}[0], "\n";
print ${$complex->{hashreference}}{"fruit"}, "\n";
$complex->{sub}->("Subroutine call.\n");
$complex->{anonymoussub}->("Anonymous subroutine call.\n");
print {$complex->{handle}} "Text printed to a handle.", "\n";
Using hash reference to retrieve value from hash
$hash{fruit} = apple;
$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
$hashref = \%hash;
print $hashref->{sandwich};
Using 'if exists' to check the entry in hash
#!/usr/bin/perl -w
use strict;
my %where = (
A => "AA",
B => "BB",
C => "CC",
D => "DD"
);
print "A!\n" if exists $where{A};
Using keys function with hash reference variable
#!/usr/bin/perl
use strict;
use warnings;
my %hash = ( A => "AA",
B => "BB",
C => "CC",
D => "DD",
E => "EE" );
my $hashReference = \%hash;
foreach ( keys( %$hashReference ) ) {
print( "The $_ goes $hashReference->{ $_ }.\n" );
}
Using map with hash
$hash{fruit} = apple;
$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
print map "$_ => $hash{$_}\n", keys %hash;
Using references to a hash.
#!/usr/bin/perl
%month = (
'01', 'Jan',
'02', 'Feb',
'03', 'Mar',
'04', 'Apr',
'05', 'May',
'06', 'Jun',
'07', 'Jul',
'08', 'Aug',
'09', 'Sep',
'10', 'Oct',
'11', 'Nov',
'12', 'Dec',
);
$pointer = \%month;
printf "\n Address of hash = $pointer\n ";
foreach $i (sort keys %$pointer) {
printf "$i is $$pointer{$i} \n";
}
Using the array as the hash value
$string = "Here's a string.";
@array = (1, 2, 3);
%hash = ('fruit' => 'apples', 'vegetable' => 'corn');
sub printem
{
print shift;
}
$complex = {
string => $string,
number => 3.1415926,
array => [@array],
hash => {%hash},
arrayreference => \@array,
hashreference => \%hash,
sub => \&printem,
anonymoussub => sub {print shift;},
handle => \*STDOUT,
};
print $complex->{string}, "\n";
print $complex->{number}, "\n";
print $complex->{array}[0], "\n";
print $complex->{hash}{fruit}, "\n";
print ${$complex->{arrayreference}}[0], "\n";
print ${$complex->{hashreference}}{"fruit"}, "\n";
$complex->{sub}->("Subroutine call.\n");
$complex->{anonymoussub}->("Anonymous subroutine call.\n");
print {$complex->{handle}} "Text printed to a handle.", "\n";
Using the each operator to extract a key/value pair as a list from the hash
#!/usr/bin/perl -w
# Associative array or hash access with each.
$hash{"Name"} = "G ";
$hash{"Address"} = "1";
$hash{"City"} = "W";
# Access each element with each.
while ( ($key,$value) = each(%hash) ) {
print "Key: $key \t Value: $value\n";
}
Using the => operator.
#!/usr/bin/perl
%weekday = (
'01' => 'Mon',
'02' => 'Tue',
'03' => 'Wed',
'04' => 'Thu',
'05' => 'Fri',
'06' => 'Sat',
'07' => 'Sun',
);
$pointer = \%weekday;
$i = '05';
printf '$$pointer{$i} is ';
printf "$$pointer{$i} \n";
printf '${$pointer}{$i} is ';
printf "${$pointer}{$i} \n";
printf '$pointer->{$i} is ';
printf "$pointer->{$i}\n";
printf '${$pointer{$i}} is ';
printf "${$pointer{$i}} \n";
printf '${$pointer->{$i}} is ';
printf "${$pointer->{$i}}";
Using values function to get all value in a hash
#!/usr/bin/perl -w
use strict;
my %where = (
A => "AA",
B => "BB",
C => "CC",
D => "DD"
);
foreach (values %where) {
print "someone lives in $_\n";
}
Using variable as the key to get the value stored in a hash
#!/usr/bin/perl -w
use strict;
my $who = "C";
my %where = (
A => "AA",
B => "BB",
C => "CC",
D => "DD"
);
print $where{A}, "\n";
print "$who lives in $where{$who}\n";
Using while and each function to output value in a hash
$hash{fruit} = orange;
$hash{sandwich} = club;
$hash{drink} = lemonade;
while(($key, $value) = each(%hash)) {
print "$key => $value\n";
}
Values operator extracts all the values of a hash
#!/usr/bin/perl -w
# Associative array or hash values.
$hash{"Name"} = "G ";
$hash{"Address"} = "1.";
$hash{"City"} = "W";
@values = values(%hash);
print "Values are: @values\n\n";
While loop and hash key value pair
#!C:/perl/bin
%animals = ('R', 'H', 'J', 'S', 'K', G);
while (($key, $value) = each %animals)
{
print "$key, $value\n";
}
Working join with map
print join(", ", (map {my $value = $_; $value *= 2} (1 .. 10)));