Day 3

Hash in PERL:

• Scalars are single data entities. Arrays are ordered collections of data entities. A hash is an unordered collection of data which may contain many sets of data, but there is no “first” or “last”, no “top” or “bottom” item in a hash.
• Hash data is always in pairs
• Hashes are treated much like lists, but the hash variable is used. Hash variables all start with %.
• Sometimes called associative arrays, dictionaries, or maps; hashes are one of the data structures available in Perl.
• A hash is an un-ordered group of key-value pairs.
• The keys are unique strings.
• The values are scalar values.
• Each value can be a number, a string, or a reference.

Creating a hash in PERL
• A hash is created in the same way as a list:
%hash1=(“Intel”, “Pentium”, “AMD”, “Athlon”, “Transmeta”, “Crusoe”);
• To help readability, the hash is usually laid out in its declaration:
%hash1=(“Intel”, “Pentium”,
                “AMD”, “Athlon”,
                “Transmeta”,“Crusoe”);
• This shows the pairing of hash data more clearly

The => operator in PERL
• To make relationships in hashes clearer, Perl allows the use of the => operator, which Perl interprets to mean a double-quoted string and acomma. This:
%hash1=(“Intel”, “Pentium”,
                “AMD”, “Athlon”,
                “Transmeta”,“Crusoe”);
becomes this:
%hash1=(Intel => Pentium,
                AMD => Athlon,
                Transmeta => Crusoe);
#===================================================================
#Example1: Demo for creating and accessing the hash table
#===================================================================
%hash1=("Intel", "Pentium",
                "AMD", "Athlon",
                "Transmeta","Crusoe");
%hash2=(Intel => Pentium,
                AMD => Athlon,
                Transmeta => Crusoe);

#Read single data from hash table
#syntax: $Hash{key}
#eg:
print $hash1{Intel},"\n";
print $hash2{AMD},"\n";

#Showing all the keys and values using keys and values functions:

print keys(%hash1),"\n";
print values(%hash1), "\n";

print "\n";
#Displaying all the keys
                print "The key values in hash1 are: \n";
for (keys(%hash1))
{
                print "$_\n";
}
#displaying all the values

for (keys %hash2)
{
                print "The hash values at key $_ is: $hash2{$_}\n";
}
#===================================================================
#Example2: Demo assigning the value of array to hash and vice-versa
#===================================================================
@os=(unix,linux,winx,aix,mac,bsd);
print "the size of array is: ",scalar(@os),"\n";

%hash=@os;
print "Printing the hash value: \n";
for (keys(%hash))
{print "$hash{$_}","\n"};
<<ABC;
When we assign an array value to hash we get random hash table like:
Key        Value
--------------
unix       linux     
mac        bsd        
winx      aix         
ABC
@array=%hash;
print "the size of array is: ",scalar(@array),"\n";
print "the array is @array\n";

#adding new value to hash
$hash{dos}="MSDOS";
print "Printing the hash value after inserting a new value: \n";
for (keys(%hash))
{print "$hash{$_}","\n"};
#===================================================================
#Example3: Deleting a value from hash table
#===================================================================
%hash1=("Intel", "Pentium",
                "AMD", "Athlon",
                "Transmeta","Crusoe");

#Displaying all the keys and values
for (keys(%hash1))
{
                print "The value at key:$_ is $hash1{$_}\n";
}

#deleting a value using the delete function
#syntax: delete($hashname{key})
delete($hash1{"AMD"});

print "After perfroming delete\n";
#Displaying all the keys and values
for (keys(%hash1))
{
                print "The value at key:$_ is $hash1{$_}\n";
}

#===================================================================
Reversing hashes in PERL
• You can use the reverse function on a hash to reverse the pairs, converting the value to a hash key and the hash key to a value. This allows you to look up with either value:
reverse %hash;
• Reversing a hash swaps the hash key and value, not the order of the pairs in the hash
• Be careful when using reverse. Since all hash keys have to be unique, there is the chance of losing some data if the values are the same prior to reversing.

Removing all the values from a hash:
Lets define a hash as:
%hash1=("Intel", "Pentium","AMD", "Athlon","Transmeta","Crusoe");
To remove all the values of hash lets redefine the hash as follows:
%hash1=();
#===================================================================
#Example4: Demo to use each and exists function
#===================================================================
#The each function returns one key and value pair
#Next time, when the each function is used, it fetches next pair of key and values
%hash=(name,ravi,empid,1234,company,oracle);

while(($k,$v)=each(%hash))
{
                print "key: $k and value: $v\n";
}
#exists function checks if there exists a data corresponding to a key
#exists($hash{key})

if (exists($hash{name}))
{print "The name is $hash{name}\n";}
else
{print "invalid key\n";}
#===================================================================
#Example5: Sorting hash based on keys
#===================================================================
%student=(ravi,100,rani,95,raju,90,khushi,99);
#printing in the ascending order
print "Sorted by name asecending order\n";
for(sort(keys(%student)))
{
                print "$_ $student{$_}\n";
}
print "Sorted by name descending order\n";
#printing in the descending order
for(sort({$b cmp $a}keys(%student)))
{
                print "$_ $student{$_}\n";
}
print "Sorted by the value ascending order\n";
for(sort({$student{$a}<=>$student{$b}}keys(%student)))
{
                print "$_ $student{$_}\n";
}
#===================================================================

Reference in PERL:
• Every variable in Perl has a value assigned in memory. Any value assigned to that variable is contained in that memory. For example, the statement:
$num1=10;
will have a memory location assigned with the name $num1, and a value of 10 is stored in that memory location.
• A reference is another variable, and has an assigned memory location, but holds the address of the $num1 memory location instead of a value.

Creating a reference in PERL:
• References are created exactly the same way as other variables, and have no special naming convention. To assign a value to the reference, you use the backslash:
$refnum1=\$num1;
• This will create a reference variable called $refnum1which will hold the memory address of the variable $num1. Creating a reference to a variable doesn’t affect the variable in any way.

 Dereferencing a Hash in PERL:
• To use the value a reference is pointing to, you have to tell the interpreter that you don’t want to know the memory address it holds, but the value inside the memory address it points to. This is done with the dereferencing operator.
For example:
print $refnum1;
will print the memory address $refnum1 holds, but
print $$refnum1;
will print the value in the memory address of

Examples:

$sr=\$s;# (scalar referencing)
$$sr; #(scalar dereferencing)

$ar=\@a;# (array referencing)
@$ar; #(array dereferencing)

$hr=\%h;# (hash referencing)
%$hr ;#(hash referencing)

There are 6 kinds of references in PERL:
1. scalar references
2. array references
3. hash  references
4. reference references
5. code/Sub-routine reference
6. Global/file handle reference
#===================================================================
#Example6: Reference demo
#===================================================================

$s="ravi"; #scalar variable
@a=(ravi,raju,khushi,rani); #array variable
%h=(ravi,90,raju,95,khushi,98,rani,97); #hash variable

$sr=\$s;# (scalar referencing)
print "Referencing a scalar $sr\n";
print "Dereferencing a scalar $$sr\n"; #(scalar dereferencing)

$ar=\@a;# (array referencing)
print "\nReferencing an array $ar\n";
print "Dereferencing an array method1: @$ar\n"; #(array dereferencing)
$count=1;
print "Dereferencing an array method2:\n";
for($count..scalar(@$ar))
{
                print "@$ar[$count-1]\n";
                $count++;
}

$hr=\%h;# (hash referencing)
print "\nReferencing a hash $hr\n";
print "Dereferencing a hash method1: \n$$hr{ravi}\t$$hr{raju}\t$$hr{khushi}\t$$hr{rani}\n";#(hash dereferencing)
print "Dereferencing a hash method2: \n";
while(($k,$v)=each(%$hr))
{
                print "key: $k and value: $v\n";
}

print "\nRefrence to a reference:\n";

$s=10;
$rv1=\$s;
$rv2=\$rv1;

print "Scalar value: $s\n";
print "Reference value of first refernce $rv1\n";
print "DeReference value of first refernce $$rv1\n";
print "Reference value of 2nd refernce $rv2\n";
print "DeReference value of 2nd refernce $$rv2\n";
print "DeReference value of 2nd refernce $$$rv2\n";


<<ABC;
Output:
D:\perl\day3>perl 6.pl
Referencing a scalar SCALAR(0x326c28)
Dereferencing a scalar ravi

Referencing an array ARRAY(0x326c70)
Dereferencing an array method1: ravi raju khushi rani
Dereferencing an array method2:
ravi
raju
khushi
rani

Referencing a hash HASH(0x326d30)
Dereferencing a hash method1:
90      95      98      97
Dereferencing a hash method2:
key: ravi and value: 90
key: raju and value: 95
key: rani and value: 97
key: khushi and value: 98

Refrence to a reference:
Scalar value: 10
Reference value of first refernce SCALAR(0x326c28)
DeReference value of first refernce 10
Reference value of 2nd refernce REF(0x327600)
DeReference value of 2nd refernce SCALAR(0x326c28)
DeReference value of 2nd refernce 10
ABC
#===================================================================
#Example7: File Handler Reference Demo
#===================================================================
open(FH,"<5.pl") or die($!);
print"\n-----------------------------------------------------------\n";
$FHR=\*FH;
print "File handler reference variable value: $FHR\n";
while(<$FHR>)
{
                print "$. $_";
}

close(FH);
#===================================================================
#Example8: Type of reference using ref function
#===================================================================
$s=10;
@a=(A..E);
%h=(key,value);

$sr=\$s;
$ar=\@a;
$hr=\%h;
$rr=\$hr;
open(FH,"<5.pl") or die($!);
$gr=\*FH;

print "Ref: ",ref($sr),"\n";
print "Ref: ",ref($ar),"\n";
print "Ref: ",ref($hr),"\n";
print "Ref: ",ref($rr),"\n";
print "Ref: ",ref($gr),"\n\n";

print "Non-Ref: ",ref(\10),"\n";

close(FH);
#===================================================================

Functions in PERL:: in built functions.
Subroutine in PERL:: user defined functions
Methods in PERL:: In oops sub-routines are called method

Creating a subroutine in PERL:
sub sub_name
{ statements…
}

Running a subroutine in PERL:
• To run a subroutine in Perl, you can use one of two syntaxes:
subname();
or
&subname();

• The ampersand is optional in almost all cases, as is most commonly left off. If you are passing parameters to the subroutine, they would be enclosed in the parentheses.
• Subroutines can call other subroutines, or themselves recursively.

#===================================================================
#Example9: Demo of sub-routines
#===================================================================
sub hello
{
#The arguments passed to the sub-routine is saved under inbuilt array @_
        print "This is hello function block\n";
        print "List of args: \n@_\n";
        for (@_)
        {
                print "$. arg: $_\n";
        }
#Getting three arguments from array @_ and saving it in a list
        ($v1,$v2,$v3)=@_;
        print "$v1 $v2 $v3\n";
}

sub display
{
        #print all the arguments
        print "@_\n";
        #saving the references under the variables
        ($r1,$r2,$r3,$r4)=@_;
        #Dereference the arrays and display its value
        print "@$r1\n";
        print "@$r2\n";
        print "@$r3\n";
        #Dereference of hash and display its value
        while(($k1,$v1)=each(%$r4))
        {
                print "key: $k1 value:$v1\n";
        }
}

#calling the hello subroutine and passing the arguments by value
hello(12..15,A..D,"UNIX");
@sh=(bash,ksh,csh,sh,tcsh);
@no=(10,12,13,14);
@names=(ravi,kumar,ram);
%h=(Key1=>Value1,key2=>value2);
#calling the display subroutine and passing the arguments by reference
display(\@sh,\@no,\@names,\%h);

print "Exit from $0..file\n";
Output:
$ perl example9.pl
This is hello function block
List of args:
12 13 14 15 A B C D UNIX
 arg: 12
 arg: 13
 arg: 14
 arg: 15
 arg: A
 arg: B
 arg: C
 arg: D
 arg: UNIX
12 13 14
ARRAY(0x8f3a29c) ARRAY(0x8f3a314) ARRAY(0x8f3a380) HASH(0x8f3a3e0)
bash ksh csh sh tcsh
10 12 13 14
ravi kumar ram
key: key2 value:value2
key: Key1 value:Value1
Exit from example9.pl..file

No comments:

Post a Comment