Perl Tutorial – II
By Rahul Jain
Tutorial Organization
Subroutines More on Control Structures Files Directory Operations File & Directory Manipulation Process Management
Subroutines
To define your own subroutine, use the keyword ‘sub’
Can be defined anywhere in your program If two subroutines have same name, the later one overwrites the earlier one
Subroutines
e.g.:
sub adder { $count += 1; print “Current value of count: $count \n”; }
Invoking a Subroutine
&adder #says Current value of count: 1 &adder #says Current value of count: 2
Subroutines
Return values
The last calculation performed or the last expression evaluated in a subroutine is automatically the return value Just like other programming languages, Perl also supports the return keyword
Subroutines
sub adder { $count += 1; } $count = 0; $c = &adder; print “Current value of count: $c \n”; $c = 2 * &adder; print “Current value of count: $c \n”;
Subroutines
sub max { if($x > $y) { $x; } else { $y; } } $x = 3; $y = 7; $result = &max; print “The max of the two nums is: $result\n”; What will be the output ?
The max of the two nums is: 7
Subroutines
Arguments
$result = &max(3, 7);
The list of parameters are stored as a array variable - @_ @_ is local to the subroutine $_[0] – first parameter $_[1] – second parameter …
Subroutines
sub max { if($_[0] > $_[1]) { return $_[0]; } else { return $_[1]; } }
$result = &max(11,12);
Subroutines
Private variables in Subroutines
sub max { my($a, $b) = @_ if($a > $b) { return $a; } else { return $b; } }
Subroutines
sub max { if($_[0] > $_[1]) { return $_[0]; } else { return $_[1]; } } $result = &max(11, 12, 13); Print “The largest number is: $result \n”;
What is the output ?
The largest number is: 12
More on Control Structures
unless
It is the opposite of if
e.g.:
unless ($attendees < 50) { print “Deny Entry \n”; }
if ($attendees < 50) { #Do Nothing } else { print “Deny entry\n”; }
More on Control Structures
until
Opposite of while loop The loop runs as long as the condition is false
e.g.:
$j = 2; $i = 12; until ($j > $i) { $j *= 2; print “$j \n”; }
More on Control Structures
elseif
Similar to nested if’s in C
Autoincrement (++) and Autodecrement (--) operators for
Same as that in C
More on Control Structures
last
Similar to break operator in C
next
Similar to continue operator in C
Logical Operators
Logical AND operator (&&) Logical OR operator (||)
Files
Filehandles are used to access files from within a program
A filehandle can be named using letters, digits and underscore. However they cant start with a digit
Files
Opening a Filehandle
open filehandle, “filename” open open open open input_file, “data”; input_file, “result”; output_file, “>>result”;
$filename = “result”; open output_file, “> $filename”;
Files
Closing a Filehandle
close filehandle e.g.:
close input_file;
Files
die
Prints the message and makes sure that the program exits cleanly
e.g.:
unless (open output_file, “>>result”) { die “Error opening output file\n”; }
Files
Using Filehandles
while() { …… } $one_line = ;
Files
File Tests
-e : File or directory name exists
-s : File or directory exists and has nonzero size -M : Modification age (measured in days)
die “A file called $filename already exists \n” if –e $filename;
Directory Operations
Program runs with a working directory This directory is that starting point for relative pathnames
The chdir operator changes the working directory
chdir “/home” or die “Error changing dir\n”;
Directory Operations
Directory Handles
Similar to filehandles
my $dir_name = “/home/xyz”; opendir DH, $dir_name or die “Error opening dir\n”; foreach $file (readdir DH) { print “File in $dir_name is $file \n”; } closedir DH;
File & Directory Manipulation
Removing a File
unlink :
Similar to the Unix command rm Can take 1 or more filenames as input parameter The return value is the number of files successfully deleted Default return value is zero
File & Directory Manipulation
unlink(“/etc/passwd”); unlink(“input”, “output”);
print “Enter file to be deleted: “; chomp($fn = ); unlink($fn);
foreach $file (<*.tmp>) { unlink($file) || warn “Having trouble deleting $file: $!”; }
File & Directory Manipulation
Renaming a File
rename: Similar to mv command of Unix rename($old, $new)
rename(“out”, “out.old”); rename(“out”, “/tmp/old”);
Note that we have to specify the filename when giving the complete directory path
File & Directory Manipulation
Creating Directories
mkdir mkdir(dirname, MASK)
MASK specifies the directory permissions Default is 0777
mkdir(“project”, 0777);
File & Directory Manipulation
Deleting Directories
rmdir rmdir(dirname)
rmdir(“project”); rmdir($dir);
File & Directory Manipulation
Modifying Permissions
chmod chmod(MASK, file1, file2,…)
Similar to chmod command of Unix Return value is number of files successfully adjusted
File & Directory Manipulation
chmod(0666, “input”, “output”);
foreach $file (“input”, “output”) { unless(chmod(0666, $file)) { warn “Problem changing permission of $file”; } }
Process Management
Use system function to launch a new process from within a Perl program The function hands a single string to the shell to execute You can direct the output of the command to either the display screen or a file Multiple commands can be specified, separated by semicolon or newline Zero is returned if the command executed without any problems
Process Management
system(“date”); #Output to STDOUT system(“date > cmd_out”); #Output to file cmd_out
system(“date; w”);
$i=0;
$file = “cmd_out.”.++$i; system(“date; w > $file”); $i=0; $file = “cmd_out.”.++$i; system(“ (date; w) > $file”);
Process Management
Backquotes
Alternate way to launch process Put the command name within backquotes ‘ ` ’
$time = “Time is: “.`date`; # Time is: Thu Mar 3 01:00:57 EST 2005
Process Management
Processes as Filehandles
Can create processes with the open command used for filehandles We can read the output of the command or give input to it
open(filehandle, “cmd |”) #open cmd for reading open(filehandle, “| cmd”) #open cmd for writing
Process Management
open(LF, “ls –lt |”); @files = ;
open(LPR, “| lpr –Pprinter1”); open(RPT, “report”); print LPR RPT;
print LPR ;
close(LPR); close(RPT);
Process Management
open(LF, “ls –lt |”); open(LPR, “| lpr –Pprinter1”);
while( ) { unless (/passwd/) { print LPR $_; } } close(LPR); close(LF);
Process Management
exec
Similar to system command Replaces the current process with the shell Hence, after a successful exec, the Perl program is gone
exec(“date”);
References
http://www.india-seo.com/perl/learn/index.htm