File handling
Coverage
§ Open / close a file
§ Reading from a file
§ Writing on to a file
§ File associated library functions
1
Basic I/O
§ STDIN, STDOUT and STDERR
§ STDIN – Reads program input. Default is the computer’s KB
Examples:
– $a = <STDIN>;
– while (defined($line = <STDIN>))
{ # process $line here }
§ STDOUT - Displays program output.
Examples:
– print(list of arguments);
– print “text”;
– printf ([HANDLE], format, list of arguments);
§ STDERR - Displays program errors. Most of the time, it is
equivalent to STDOUT.
2
Command line arguments
§ Command line arguments in Perl are extremely easy.
§ @ARGV is the array that holds all arguments passed in from the
command line.
– Example:
– ./prog.pl arg1 arg2 arg3
– @ARGV would contain ('arg1', ‘arg2', 'arg3’)
§ $#ARGV returns the number of command line arguments that have
been passed.
@ARGV
$ARGV[index]
scalar(@ARGV) è holds number of elements
3
Command line arguments - Example
#!/usr/bin/perl
my $argc;
$argc = scalar(@ARGV); #Save the number of command line parameters.
if(scalar(@ARGV) == 0)
{
print "Usage: perl perlParams.pl param01 [param02 ... param0n]\n";
exit(0);
}
print "Hello World!\n";
print "You have passed $argc parameters\n";
for (my $i=0;$i<$argc;$i++)
{
print "parameter $i: ",$ARGV[$i],"\n";
}
4
File I/O - Introduction
Filehandle
§ Automatic filehandles: STDIN, STDOUT and STDERR
§ Syntax:
open(<handle name>,”(<|>|>>)filename”);
close(<handle name>);
§ Example:
open(INPUTFILE,”<inputs.txt”); #opens file handle
…
Close(INPUTFILE); #closes file handle
§ Handle access does not always yield true
§ Check for return value of the open function
§ Example:
– if(open(INPUT,”<inputs.txt”))
… #do something
else
print “File open failed\n”;
5
Reading from a file (contd..)
§ <STDIN> reads from the keyboard # stdin is the file handle
§ < > reads from the files on the command line
§ If no files are specified there then it reads from the STDIN
§ $_ is the default variable in which data is read into if no variable is
provided
6
File Reading
Reading from a file
$line = <>;
§ < > operator is used to read from a file handler
§ <> reads one line from the “current file”
while( $line = <> ) { while(<> ) { while(<FH> ) {
print $line; print $_; print $_;
} } }
§ Repeats the statements between { and } while there is another line.
§ The syntax is $variable = <FILEHANDLE >
7
File Reading - Example 1 – Managing File Name
8
File Reading - Example 2 – Managing File Contents
9
File Handling - Functions
Read function
§ The read function read n number of bytes of characters from a file
§ read ( file handle , $scal , n )
§ The second parameter is the scalar variable where the content read
from the file is returned
§ It returns the number of bytes actually read
eof() function
§ This function tests if the file pointer to file specified by the file
handle is at the end of the file
§ If no argument is supplied the file tested is the last file that was read
10
File Reading - Example 3 – Using eof() function
11
Writing to a file
§ Print is used to write to a file
§ Print FILEHANDLE list
Eg : $\ = “\n”;
open (FH, ">myfile.txt");
print FH “line1”; print FH “ line2”;print FH “ line3”;
12
Close ( ) function
§ close( ) function is used to close the file in that mode
§ It also delinks the filehandle from that file
§ The filehandle can be used for a different file now
§ close ( FILEHANDLE )
§ It is optional
13
File test operators
§ There are some test operators that tests the aspects of a file
§ Test operator operand
§ The operand can be either a filehandle or a filename
§ Way to use a test operator
if ( -e “myfile.txt”) # -e is a test operator to check if a
{ # file exists
open ( FH , “myfile.txt”) ;
}
14
Die and warn functions
§ The die() function is used to quit the script
§ After termination it displays a message for the user to read.
§ Its syntax is die (LIST) ;
§ The elements of LIST are printed to STDERR .
§ It sets the script's return value to $! (errno) .
§ The warn( ) function has the same functionality as die( )
§ The sole exception is the script is not exited.
§ This function is better suited for non-fatal messages
§ The $! variable is used to display the system error message.
15
Unlink function
§ unlink deletes a file
§ unlink ( FILE )
§ If FILE is not specified, then $_ will be used.
§ Therefore, it returns false or 0 if no file was deleted.
16
Special variables
§ $0 - Name of the currently executing script.
§ $$ - Current pid.
§ $! - The current system error message from errno.
§ $_ - Default for pattern operators and implicit I/O
§ $. - The current input line number of the last filehandle that was read.
Reset when the file handle is closed.
17
Running Other Programs from Perl
$files = `ls`;
The "backtic" (` `) characters execute the text in between as a
command to the operating system, returning the output of that
command (e.g. to the $files) variable.
$error = system( "mv $file ${basefile}.abi" );
The system statement executes its argument as a command to the
operating system, returning ERROR MESSAGES from that command.
(Output is printed as usual.) There are other, subtle differences
between ` ` and system.
18
Directory-Manipulation Functions
Directory Reading Routines
§ mkdir () mkdir (dirname, permissions);
– For example, to create a directory named /u/jqpublic/newdir, you can use the
following statement:
mkdir ("/u/jqpublic/newdir", 0777);
– To create a subdirectory of the current working directory, just specify the new
directory name, as follows:
mkdir ("newdir", 0777);
§ opendir() opendir (dirvar, dirname);
– For example, to open the directory named /u/janedoe/mydir, you can use the
following statement:
opendir (DIR, "/u/janedoe/mydir");
§ closedir() closedir (dirvar);
§ readdir() readdir (dirvar);
19
Sample Examples
20