Upload
kharels
View
236
Download
0
Embed Size (px)
Citation preview
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 1/30
Copyright © Amstar Technologies 1
PPracticalractical EExtraction &xtraction & RReporteportLLanguageanguage
By:B.T.R NaiduB.T.R Naidu
Email: [email protected]
Copyright © Amstar Technologies
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 2/30
Copyright © Amstar Technologies 2
PERL
Arrays & Hashes
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 3/30
Copyright © Amstar Technologies 3
Data Types Arrays
Arrays – Different types of scalarscan be stored in a single array.
Declare: @variableName;
Assign:@varName = (elem1, elem2, …, elemN);
Index: $variableName[index]• Index starts at 0 just like in C
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 4/30
Copyright © Amstar Technologies 4
Data Types Arrays
We can create an array by assigning a list to a variable like this@array=(1,2,3);
To see the result, we can print out the new array
print @array; # Output: 123
We can also refer to individual array elements by index usingsquare brackets and prefacing the name of the element with $,because it’s a scalar
@array = (1, 2, 3);print $array[0]; # Output: 1
Besides numbers, we can also store other types of scalars, like
strings@array = (“one”, “two”, “three”);
print @array; # Output: onetwothree
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 5/30
Copyright © Amstar Technologies 5
Data Types Arrays
Note: Because Perl skips over white space (including Newlines)when handling lists, we can set up our array assignment this wayas well.
@array = (
“one”, “two”, “three”,
“four”, “five”, “six”,
);
print @array; # Output: onetwothreefourfivesix
We can also use the x repetition operator, as in this case, whichcreates an array of 100 zeroes.
@array = (0) x 100;
And we can use quote operators like qw.@array = qw(one two three);
print @array; # Output: onetwothree
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 6/30
Copyright © Amstar Technologies 6
Data Types Arrays
Note: Although arrays are zero based by default, we canactually change the base by placing a new value in the Perlspecial variable $[.
We can vary a loop index to work through every value in anyarray
@array = (“one”, “two”, “three”);
for ($loop_index=0; $loop_index<=$#array; $loop_index++)
{print $array[$loop_index];
}
Output: onetwothree
Note: The use of the value $#array, which, in Perl, is the lastindex in the array @array.
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 7/30
Copyright © Amstar Technologies 7
Data Types Arrays
Besides using list assignments, we can use the push and popfunctions to work with arrays.
The push function adds a value, or values to the end of an array
push ARRAY, LIST
The length of the ARRAY increases by the length of LIST.
The pop function get a value from an array
pop ARRAY
In particular, this function pops ( removes and returns ) the lastvalue of the array, shortening the array by one element.
Example for push:
push(@array, “one”);
push(@array, “two”);
push(@array, “three”);
print $array[0]; # Output: one
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 8/30
Copyright © Amstar Technologies 8
Data Types Arrays
Example for pop:@array = (“one”, “two”, “three”);
$var1 = pop(@array);
print $var1; # Output: three
shift and unshift do to the left end of the array with pushand pop do to the right end.
The shift function shifts the first value of the array off and
returns it, shortening the array by one element and movingeverything down one place
shift ARRAY
This unshift function does the opposite of shift; it adds LISTto the front of the array and returns the new elements inthe array.
unshift ARRAY, LIST
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 9/30
Copyright © Amstar Technologies 9
Data Types Arrays
Finding The Length of ArraysWhen we have an array names, say,
@array, then the expression $#arrayholds the last index value in the array.
We can display the number of elements inthis array by adding 1 to $#array:
@array = (1, 2, 3);print “\@array has “.($#array+1).” Elements.”;
Output: @array has 3 elements
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 10/30
Copyright © Amstar Technologies 10
Data Types Arrays
Using an array in a scalar context also returns itslength.
To put an array in a scalar context, we can dosomething numeric that has no effect, like addinga zero to it, such as
@array + 0
or; more professionally, we can use the scalarfunction:
@array = (1, 2, 3);
print “\@array has “.scalar(@array).” Elements.”;
Output: @array has 3 elements.
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 11/30
Copyright © Amstar Technologies 11
Data Types Arrays
Growing Or Shrinking Arrays We can change the number of elements in an array simply by
changing the value of the last index value in the value $#array.
@array = (1, 2, 3);
$#array = 10;$array[5] = “Here is a new element!”;
print “$array[5]\n”;
Output: Here is a new element!
In fact, if you simply refer to a nonexistent element in anarray, Perl extends the array as needed, creating newelements up to and including the new element:
You can empty an array by setting its length to a negativenumber:$#array = -1;
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 12/30
Copyright © Amstar Technologies 12
Data Types Arrays
Merging Two Arrays We can merge two arrays with a list assignment.
@array1 = (1, 2, 3);
@array2 = (4, 5, 6);
@bigarray = (@array1, @array2);
print $bigarray[5]; #Output:6
Getting Array Slices
An array slice is a section of an array that we can createwith the range operator.
The range operator works like this: [x..y]. Here, we arereferring to the array elements x, x+1, all the way up to y.
@array = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
@array2 = @array[2..3];
print join(“, “, @array2);
Output: 3, 4
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 13/30
Copyright © Amstar Technologies 13
Data Types Arrays
Looping Over Arrays Using for loop
@array = (“one”, “two”, “three”);
for($loop_index = 0; $loop_index <= $#array; $loop_index++){
print $array[$loop_index];
}
Output: onetwothree
Using foreach loop@array = (1, 2, 3, 4, 5);
foreach $element (@array) {
print “$element\t”;
}
Output: 1 2 3 4 5
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 14/30
Copyright © Amstar Technologies 14
Data Types Arrays
In fact, you can loop over several arrays at thesame time by creating a list of arrays.@array = (1, 2, 3);
@array2 = (4, 5, 6);
foreach $element (@array, @array2) {
print “$element\t”;
}
Output: 1 2 3 4 5 6
Besides foreach, you can use a for loop
@array = (1, 2, 3, 4, 5);
for $element (@array) {
print “$element\t”;
}
Output: 1 2 3 4 5
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 15/30
Copyright © Amstar Technologies 15
Data Types Arrays
When you want to, you can use a for loop withoutspecific reference to the elements in the loop atall, using the default variable $_:
@array = (1, 2, 3, 4, 5);
for (@array) {
print;
}
Output: 12345
Printing ArraysWhen you just want to print an array, you can
pass it to the print function this way@array = (“one”, “two”, “three”);
print “Here is the array: @array.\n”;
Output: Here is the array: one two three.
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 16/30
Copyright © Amstar Technologies 16
Data Types Arrays
If you want to display a comma between eachelement in the array then use the join functionlike this -
@array = (“one”, “two”, “three”);
print join(“, “, @array);Output: one, two, three
You are also free to explicitly loop over all theelements in the array using for or foreach -
@array = (“one”, “two”, “three”);
foreach $element (@array) {
print “Current element = $element\n”;
}
Output: Current element = one
Current element = two
Current element = three
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 17/30
Copyright © Amstar Technologies 17
Data Types Arrays
Splicing Arrays Splicing an array means adding elements from a list to that
array, possibly replacing elements now in the array. You
use the splice function to splice arrays.Splice ARRAY,OFFSET,LENGTH,LIST
Splice ARRAY,OFFSET,LENGTH
Splice ARRAY,OFFSET
The splice function removes the elements indicated byOFFSET and LENGTH from an array and replaces them withthe elements of LIST, when you specify a list.
@array = (“one”, “two”);splice(@array, 2, 0, “three”);
print join(“, “, @array);
Output: one, two, three
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 18/30
Copyright © Amstar Technologies 18
Data Types Arrays
We can also splice a new array onto the end of an old one@array = (“one”, “two”);
@array2 = (“three”, “four”);
splice(@array, 2, 0, @array2);
print join(“, “, @array);
Output: one, two, three, four
We can also replace elements in an array that we aresplicing
@array = (“one”, “zero”);
@array2 = (“two”, “three”, “four”);splice(@array, 1, 1, @array2);
print join(“, “, @array);
Output: one, two, three, four
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 19/30
Copyright © Amstar Technologies 19
Data Types Arrays
Reversing Arrays To reverse an array, you simply use the reverse
function.
@New = reverse @array;
Sorting Arrays To sort an array, you use the sort function.
@new = sort {$a <=> $b} @array; Here’s an array sorted in descending order.
@new = sort {$b <=> $a} @array;
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 20/30
Copyright © Amstar Technologies 20
Data Types Hashes
Hashes – associative arrays; definepairs of scalars, keys then elements
Declare: %varName;Assign:• %varName = (key1, elem1, key2, elem2, … );
Index: $varName{key};
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 21/30
Copyright © Amstar Technologies 21
Data Types Hashes
As with arrays, we use the $ prefix dereferencers whenworking with individual hash elements.
Note that we use curly braces, {}, to dereference a hashelement, not square brackets, [], as we do with arrays.
%hash = ();$hash{fruit} = apple;
$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
print $hash{sandwich}; # Output: hamburger
we can create a hash like this, specifying the key/valuepairs we want to fill the hash with:
%hash = (
fruit, apple,
sandwich, hamburger,
drink, bubbly,
);
print “$hash{fruit}\n”; # Output: apple
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 22/30
Copyright © Amstar Technologies 22
Data Types Hashes
In fact, there’s a synonym for a comma: =>. Using thisoperator makes the relationship between keys and valuesclearer
%hash = (fruit => apple,
sandwich => hamburger,drink => bubbly,
);
print “$hash{fruit}\n”; # Output: apple
We can also use keys with spaces in them, as in this case,which creates a hash element with the key ice cream:
$hash2{cake} = chocolate;$hash2{pie} = blueberry;
$hash2{‘ice cream’} = pecan;print “$hash{‘ice cream’}\n”; # Output: pecan
Keep in mind that we can’t reference the values in a hashdirectly with a numeric index.
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 23/30
Copyright © Amstar Technologies 23
Data Types Hashes
Adding elements to Hashes We can create hashes using list assignments
%hash = (
fruit => apple,sandwich => hamburger,
drink => bubbly,
);
%hash = (%hash, ‘dressing, ‘blue cheese’);print “$hash{dressing}\n”;
# Output: bleu cheese
This example works because the list operator, (),interpolates %hash into a list, and then we extend that list
by one key/value pair.
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 24/30
Copyright © Amstar Technologies 24
Data Types Hashes
Checking If Hash Elements Exist To check if an element exists in a hash, we can use the
exists function.
$hash{fruit} = apple;$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
if ( exists ($hash{“vegetable”})) {
print “Element exists.”;
} else {
print “Element does not exist.”;
}
Output: Element does not exist
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 25/30
Copyright © Amstar Technologies 25
Data Types Hashes
Deleting Hash Elements To delete an element in a hash, just use the
delete function.
$hash{fruit} = apple;$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
delete($hash{“fruit”});
if ( exists ($hash{“fruit”})) {
print “Element exists.”;
} else {print “Element does not exist.”;
}
Output: Element does not exist.
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 26/30
Copyright © Amstar Technologies 26
Data Types Hashes
Looping Over Hashes
Using each function
while(($key, $value) = each (%hash)) {
print “$key => $value\t”;
}
Output: drink=>buddly sandwich => hamburger fruit => apple
Using keys function
foreach $key (keys %hash) {
print $hash{$key} . “\t”;}
Output: bubbly hamburger apple
Using values function
foreach $value (values %hash) {print $value . “\t”;
}
Output: bubbly hamburger apple
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 27/30
Copyright © Amstar Technologies 27
Data Types Hashes
Printing HashesWe can print a hash by interpolating it in
double quotes
$hash{fruit} = apple;
$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
print “@{[%hash]}\n”;
#Output: drink bubbly sandwich hamburger fruit apple
Note that this prints the hash as it list context: askey/value pairs, one after the other. A betterchoice might be to use the each function.
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 28/30
Copyright © Amstar Technologies 28
Data Types Hashes
Sorting Hashes We can use the sort function to sort a hash
$hash{fruit} = apple;
$hash{sandwich} = hamburger;
$hash{drink} = bubbly;foreach $key (sort keys %hash) {
print “$key => $hash{$key}\t”;
}
Output: Drink => bubbly Fruit => apple Sandwich => hamburger
We can also sort a hash by value instead of by key
$hash{fruit} = apple;
$hash{sandwich} = hamburger;
$hash{drink} = bubbly;
foreach $value (sort values %hash) {
print “$value\t”;
}
Output: apple bubbly hamburger
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 29/30
Copyright © Amstar Technologies 29
Data Types Hashes
Merging Two Hashes To merge two hashes, we can use a list
assignment
$hash1{fruit} = apple;
$hash1{sandwich} = hamburger;
$hash1{drink} = bubbly;
$hash2{cake} = chocolate;
$hash2{pie} = blueberry;
$hash2{‘ice cream’} = pecan;%bighash = (%hash1, %hash2);
print $bighash{‘ice cream’};
Output: pecan
7/23/2019 Perl m03 - Arrays & Hashes
http://slidepdf.com/reader/full/perl-m03-arrays-hashes 30/30
Copyright © Amstar Technologies 30