You are on page 1of 28

Perl P-3

Ramiz Ahmed
Hashes
● Associate keys with values.
● Allows for almost instantaneous lookup of a value that
is associated with some particular key.

Existing, Defined and true.


● If the value for a key does not exist in the hash, the
access to it returns the undef value.
● special test function exists(HASHENTRY), which
returns true if the hash key exists in the hash
● if($hash{$key}){...}, or if(defined($hash{$key})){...}
return false if the key $key has no associated value
Hashes Examples
#!/usr/bin/perl
# Simple List operations
$player{"clarinet"} = "Susan Bartlett";
$player{"basson"} = "Andrew Vandesteeg";
$player{"flute"} = "Heidi Lawson";
$player{"oboe"} = "Jeanine Hassel";
@woodwinds = keys(%player);
@woodwindPlayers = values(%player);
print”@woodwinds”;
print”@woodwindPlayers”;
● use warnings will output warnings to
the command line.
● It will alert you if you try to use an
undeclared variable by accident.
● It will let you know if unexpected
types or values are being used.
Scalar Variable
e.g., strings, numbers [0] 32
[1] 21.4
[2] “Fred”

Array Variable [3] “a”

e.g., list of strings, list of Scalar Var.

numbers, … “ID” 32
“time”  21.4
“name”  “Fred”

Hash Variable 4 “A”


key value
e.g., list of <key, value>s
Basic data structure : Hash function
#!/usr/bin/perl
%name = (Tom => 26, Peter => 51, Jones => 23);
@a=keys(%name);
@b=values(%name);
print"@a";
print"\n";
print"@b";
#!/usr/bin/perl
my %name=( Tom=>26 ,Peter=>51 ,Jones=>23);
@a=keys(%name);
@b=values(%name);
print ("@a");
print"\n";
print"@b\n";
print $name{"Tom"}."\n";
if(exists $name{"Tom"})
{
print("Hi,the id of Tom is",$name{"Tom"});
}
Defining subroutines

● Like any good programming langauge Perl


allows the user to define their own
functions, called subroutines.
● They may be placed anywhere in your
program but it's probably best to put
them all at the beginning or all at the
end.
● Subroutine is called with an & character
in front of the name.
#!/usr/bin/perl
sub mysubroutine
{
print "Not a very interesting routine\n";
print "This does the same thing every time\n";
}
&mysubroutine; # Call the subroutine
&mysubroutine($_); # Call it with a parameter
&mysubroutine(1+2, $_); # Call it with two
parameters
#!/usr/bin/perl
sub printfirsttwo
{
print "Your first argument was $_[0]\n";
print "and $_[1] was your second\n";
}
&printfirsttwo("A","B");
Returning values
sub maximum
{
if ($_[0] > $_[1])
{
$_[0];
}
else
{
$_[1];
}
}

$biggest = &maximum(37, 24);


@_ is an array of all the variables passed to the
subroutine

For example, if you called a function with two


arguments, those would be stored in $_[0] and $_[1]

The index of the last input would be $#_


Example of subroutine

$areaOfFirstCircle = areaOfCircle(5);
print("$areaOfFirstCircle\n");
sub areaOfCircle {
$radius = $_[0];
return(3.1415 * ($radius ** 2));
}
firstSub(1, 2, 3, 4, 5, 6);
firstSub(1..3);
firstSub("A".."Z");
sub firstSub {
$numParameters = @_ ;
print("The number of parameters is
$numParameters\n");
}
Passing Parameters to Functions

Array passing without by refrence


firstSub( (1..5),("A".."E"));
sub firstSub {
my(@firstArray, @secondArray) = @_ ;
print("The first array is @firstArray.\n");
print("The second array is
@secondArray.\n");
}
Passing by reference
#!/usr/bin/perl
@array1 = (1..5);
@array2 = ("A".."E");
firstSub( \@array1, \@array2);
sub firstSub
{
my($ref_firstArray, $ref_secondArray) = @_;
print("The first array is @{$ref_firstArray}.\n");
print("The second array is @{$ref_secondArray}.\n");
}
File Input / Output

To write a file
#!/usr/bin/perl

# this will create a new file “test.txt” to write


open MY_FILE, “>test.txt”;

# write something to the opened file


print MY_FILE “barney\n lucy\n fred\n”;

# close the file


close MY_FILE;
● To write a file

#!perl
# ------------------------------------
# FILE OUTPUT
# ------------------------------------
# this will open an existing file “test.txt” to append
open MY_FILE, “>>test.txt”;

# write something to the opened file


print MY_FILE “barney\n lucy\n fred\n”;

# close the file


close MY_FILE;
● To Read from a file

#!perl
# ------------------------------------
# FILE INPUT
# ------------------------------------
# this will open a file “test.txt” to read
open MY_FILE, “<test.txt”;
while( defined( my $line= <MY_FILE> ) ) {
print $line; # print one line read from a file
}

# close the file


close MY_FILE;
Reading Directories

opendir(DIR,“/mnt/home") or
die "NO SUCH Directory: Images";
while ($file = readdir(DIR) ) {
print " $file\n";
}
closedir(DIR);
Reading and Writing Files

open(FILE,"myfile") || die "cannot open file";


while(<FILE>)
{
print $_;
}
close(FILE);
open(IN,"infile") || die "cannot open input
file";
open(OUT,"outfile") || die "cannot open
output file";
while(<IN>)
{
print OUT $_;
}
close(IN);
close(OUT);
open(IN,"infile") || die "cannot open input
file";
open(OUT,"outfile") || die "cannot open
output file";
while(<IN>)
{
print OUT $_;
}
close(IN);
close(OUT);
Basic pattern matching

$sentence =~ /the/
True if $sentence contains "the"
$sentence = "The dog bites.";
if ($sentence =~ /the/) # is false
…because Perl is case-sensitive
!~ is "does not contain"
Square brackets
[qjk] # Either q or j or k

[^qjk] # Neither q nor j nor k

[a-z] # Anything from a to z inclusive

[^a-z] # No lower case letters

[a-zA-Z] # Any letter


More examples
[aeiou]+ # matches one or more vowels

[^aeiou]+ # matches one or more


nonvowels

[0-9A-F] # matches a single hex digit

[a-zA-Z] # matches any letter

[a-zA-Z0-9_]+ # matches identifiers


More special characters
\n # A newline
\t # A tab
\w # Any alphanumeric; same as [a-zA-Z0-9_]
\W # Any non-word char; same as [^a-zA-Z0-9_]
\d # Any digit. The same as [0-9]
\D # Any non-digit. The same as [^0-9]
\s # Any whitespace character
\S # Any non-whitespace character
\b # A word boundary, outside [] only
\B # No word boundary
THANK YOU

You might also like