File Handling: Coverage
File Handling: Coverage
Coverage
§ Open / close a file
§ Reading from a file
§ Writing on to a file
§ File associated library functions
1
Basic I/O
2
Command line arguments
@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);
}
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..)
6
File Reading
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
Eg : $\ = “\n”;
open (FH, ">myfile.txt");
print FH “line1”; print FH “ line2”;print FH “ line3”;
12
Close ( ) function
§ close ( FILEHANDLE )
§ It is optional
13
File test operators
§ There are some test operators that tests the aspects of a file
14
Die and warn functions
15
Unlink function
§ unlink ( FILE )
16
Special variables
§ $$ - Current pid.
§ $. - 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.
18
Directory-Manipulation Functions
– To create a subdirectory of the current working directory, just specify the new
directory name, as follows:
mkdir ("newdir", 0777);
19
Sample Examples
20