Session six
References
A Perl reference is a scalar data type that holds the location
of another value which could be scalar, arrays, or hashes.
Create References:
$scalarref = \$foo;
$arrayref = \@ARGV;
$hashref = \%ENV;
Dereferencing:
$var = 10; Value of 10 is : 10
$r = \$var;
print "Value of $var is : ", $$r, "\n";
@var = (1, 2, 3); Value of 1 2 3 is :
$r = \@var 123
print "Value of @var is : ", @$r, "\n";
%var = ('key1' => 10, 'key2' => 20); Value of %var is :
$r = \%var; key220key110
print "Value of %var is : ", %$r, "\n";
If you are not sure about a variable type, then its easy to
know its type using ref
$var = 10; Reference type
$r = \$var; in r : SCALAR
print "Reference type in r : ", ref($r), "\n";
References to Functions:
#!/usr/bin/perl
sub PrintHash{
my (%hash) = @_;
foreach $item (%hash){
print "Item : $item\n"; }
}
%hash = ('name' => 'Tom', 'age' => 19); .
$cref = \&PrintHash;
&$cref(%hash); # calling function Item : name
Item : Tom
Item : age
Item : 19
File I/O
The basics of handling files are simple: you associate a
filehandle with an external entity (usually a file) and then use
a variety of operators and functions within Perl to read and
update the data stored within the data stream associated
with the filehandle.
A filehandle is a named internal Perl structure that associates
a physical file with a name
Three basic file handles are - STDIN, STDOUT, and STDERR
Open Function
#!/usr/bin/perl
open(DATA, "<file.txt") or die "Couldn't open file file.txt, $!";
while(<DATA>)
{
print "$_";
}
DATA is the file handle, which will be used to read the file
Sysopen Function
sysopen(DATA, "file.txt", O_RDWR);
#Or to truncate the file before updating
sysopen(DATA, "file.txt", O_RDWR|O_TRUNC );
You can use O_CREAT to create a new file and O_WRONLY-
to open file in write only mode and O_RDONLY - to open file
in read only mode
O_RWDR, O_EXCL, and O_CREAT are all constants defined in
the Fcntl module. Put the line “use Fcntl;”
Close Function
close(DATA) || die "Couldn't close file properly";
To close a filehandle, and therefore disassociate the
filehandle from the corresponding file
Reading and Writing Files
reading
1-The <FILEHANDL> Operator:
#!/usr/bin/perl
open(DATA,"<import.txt") or die "Can't open data";
@lines = <DATA>;
close(DATA);
When you use the <FILEHANDLE> operator in a list context, it
returns a list of lines from the specified filehandle.
$name = <DATA>; ??
2-getc Function:
open(my $file , '<',”file.txt”);
$c = getc $file;
The getc function returns a single character from the specified
FILEHANDLE
while (defined($c = getc $file))
{
print $c, "\n";
}
Writing
1-Print Function:
print FILEHANDLE LIST;
The print function prints the evaluated value of LIST to
FILEHANDLE
Renaming a file
#!/usr/bin/perl
rename ("/usr/test/file1.txt", "/usr/test/file2.txt" );
rename a file file1.txt to file2.txt
Deleting an Existing File
#!/usr/bin/perl
unlink ("/usr/test/file1.txt");
Task:
Write a script which opens an existing file file1.txt and read it
line by line and generate another copy file file2.txt.
#!/usr/bin/perl
# Open file to read
open(DATA1, "<file1.txt“ );
# Open new file to write
open(DATA2, ">file2.txt");
# Copy data from one file to another.
while(<DATA1>)
{ print DATA2 $_; }
close( DATA1 );
close( DATA2 );
Format
Perl uses a writing template called a 'format' to output
reports.
format FormatName =
fieldline
value_one, value_two, value_three
fieldline
value_one, value_two
.
Fieldline:
fieldline can contain any text or fieldholders. The
fieldholders hold space for data that will be placed there at
a later date
Fieldholders:
@<<<< left-justified
@>>>> right-justified
@|||| centered
@####.## numeric field holder
@* multiline field holder
@<<<< This fieldholder is left-justified, with a field space
of 5. You must count the @ sign and the < signs to know the
number of spaces in the field.
#!/usr/bin/perl
format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
===================================
Format declaration:
select(STDOUT);
$~ = format_name;
write;
Define a Report Header:
$^ = format_name;
Example:
#!/usr/bin/perl
format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
===================================
.
format EMPLOYEE_TOP =
===================================
Name Age
===================================
.
select(STDOUT);
$~ = EMPLOYEE;
$^ = EMPLOYEE_TOP;
@n = ("Ali", "Raza", "Jaffer");
@a = (20,30, 40);
@s = (2000.00, 2500.00, 4000.000);
$i = 0;
foreach (@n){
$name = $_;
$age = $a[$i];
$salary = $s[$i++];
write; }
===================================
Name Age
===================================
===================================
Ali 20
2000.00
===================================
===================================
Raza 30
2500.00
===================================
===================================
Jaffer 40
4000.00
===================================
Error Handling
The warn Function:
The warn function just raises a warning, a message is printed
to STDERR, but no further action is taken.
chdir('/etc') or warn "Can't change directory";
The die function:
works just like warn, except that it also calls exit.
chdir('/etc') or die "Can't change directory";
Regular Expressions
There are three regular expression operators within Perl.
• Match Regular Expression - m//
• Substitute Regular Expression - s///
• Transliterate Regular Expression - tr///
The basic method for applying a regular expression is to use
the pattern binding operators =~ and !~.
1-The Matching Operator
#!/usr/bin/perl
$bar = "This is foo and again foo";
if ($bar =~ m[foo])
{ print "First time is matching\n"; }
else
{ print "First time is not matching\n"; }
First time is matching
#!/usr/bin/perl
$string = "The food is in the salad bar"; Before: The
$string =~ m/foo/; Matched :foo
print "Before: $`\n"; After: d is in the
print "Matched: $&\n"; salad bar
print "After: $'\n";
$&, which contains the entire matched string;
$`, which contains everything before the matched string;
$', which contains everything after the matched string.
2- The Substitution Operator
#/user/bin/perl
$string = "The cat sat on the mat";
$string =~ s/cat/dog/;
print "$string\n";
The dog sat on the mat
2-The Translation Operator
#/user/bin/perl
$string = 'The cat sat on the mat';
$string =~ tr/a/o/; The cot sot on the mot.
print "$string\n";
The translation replaces all occurrences of the characters in
SEARCHLIST with the corresponding characters in
REPLACEMENTLIST
To change the case of the string
$string =~ tr/a-z/A-Z/;
Thank you