Session 6
Session 6
References
Create References:
$scalarref = \$foo;
$arrayref = \@ARGV;
$hashref = \%ENV;
Dereferencing:
#!/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
#!/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
reading
1-The <FILEHANDL> Operator:
#!/usr/bin/perl
open(DATA,"<import.txt") or die "Can't open data";
@lines = <DATA>;
close(DATA);
$name = <DATA>; ??
2-getc Function:
#!/usr/bin/perl
unlink ("/usr/test/file1.txt");
Task:
format FormatName =
fieldline
value_one, value_two, value_three
fieldline
value_one, value_two
.
Fieldline:
Fieldholders:
@<<<< left-justified
@>>>> right-justified
@|||| centered
@####.## numeric field holder
@* multiline field holder
select(STDOUT);
$~ = format_name;
write;
#!/usr/bin/perl
format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
===================================
.
format EMPLOYEE_TOP =
===================================
Name Age
===================================
.
select(STDOUT);
$~ = EMPLOYEE;
$^ = EMPLOYEE_TOP;
$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:
#!/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"; }
#/user/bin/perl
$string = "The cat sat on the mat";
$string =~ s/cat/dog/;
print "$string\n";
#/user/bin/perl
$string = 'The cat sat on the mat';
$string =~ tr/a/o/; The cot sot on the mot.
print "$string\n";
$string =~ tr/a-z/A-Z/;
Thank you