In this Article we will learn the FILE IO in PERL in the sequence :
- File Input/Output in PERL
- Shorthand file open command
- Reading from a File : Two Ways
- Reading a file into an Array
- Writing into a File
- Dealing with STD I/O
- Overall Log Files for a PERL script
- Glob-ing & Unix Style File I/O in PERL
File Input/Output in PERL:
A FILEHANDLE is the name for an I / O connection between your Perl process and the I / O device.
Filehandles are ALL UPPERCASE to avoid possible collisions with present or future reserved words.
A file can be opened using : open ( filehandle, mode, filename );
A file can be closed using : close function as : close ( filehandle );
Open returns nonzero on success, the undefined value otherwise.
If the open involved a pipe, the return value happens to be the PID of the sub-process.
When opening fails, it's never a good idea to continue !
Hence we use perlfunction die to terminate the program if the file open fails.
File Handle Modes in PERL :
The Various MODE strings in "open( filehandle, mode, filename )" are tabulated below with their respective meaning :
Some Short-hands for Open Command in PERL :
Here are some pre-constructed open commands for you with their meanings in the RHS :
open(IN, "filename"); # read from existing file | |
open(IN, "<filename"); # (same thing, explicitly) | |
open(OUT, ">filename"); # create file and write to it | |
open(OUT, ">>filename"); # append to existing file | |
open(OUT, "| output-pipe-command"); # set up an output filter | |
open(IN, "input-pipe-command |"); # set up an input filter |
Reading From a File in PERL : By Example :
Testing the File On Disk Before Opening It :
Here goes a basic prototype of file open code sequence in PERL :
# Reading from a filehandle is accomplished by placing the filehandle inside <angle brackets> (the “line input operator”, or, often called as the “angle operator”). | |
my $INPUT; | |
open(INPUT, "<", "input.txt") or die "Can't open input.txt: $!"; | |
# Process every line in input.txt | |
While ( my $line = <INPUT> ) { | |
# | |
# ... process each $line here ... | |
# | |
} | |
close INPUT; # the file is closed |
The above code is self-explanatory and request you to do experiments with this at your end.
Several File Test operators can be used along with IF Condition before you open a file in/from the disk. These test cards help you to make fail-safe operation in file operation min PERL . Here is the exhaustive list :
Reading From A File : Example
Here is typical prototype of a file open routine in PERL :
# Reading from a filehandle is accomplished by placing the filehandle inside <angle brackets> (the “line input operator”, or, often called as the “angle operator”). | |
my $INPUT; | |
open(INPUT, "<", "input.txt") or die "Can't open input.txt: $!"; | |
# Process every line in input.txt | |
While ( my $line = <INPUT> ) { | |
# | |
# ... process each $line here ... | |
# | |
} | |
close INPUT; # the file is closed |
Reading a File Directly into An Array :
Writing into a File in Disk :
Opening STD I/O Through PERL File Handle :
We can directly open a file into an Array where each element of the Array is Each line of the file. Here is the short and sweet code for the same :
my INFILE; | |
open ( INFILE, $fileName ); # not using any mode means Read Mode | |
my $line = <INFILE>; # get the first line | |
my @rest = <INFILE>; # get the rest of the file | |
close INFILE; |
Here goes a short and sweet example of the write routine in PERL :
my $OUT; | |
open(OUT, ">", "output.txt") or die "Can't open > output.txt: $!"; | |
foreach my $i (1..100) { | |
print OUT "This line gets i = $i .\n"; | |
} | |
close OUT; |
Standard handles: STDIN, STDOUT, STDERR are opened by default :
print STDOUT "Enter a number: "; # ask for a number
my $number = <STDIN>; # input the number
print STDOUT "The number is $number\n"; # print the number
print STDERR "An error has occured !\n"; # print the error
EDA Automation : Creating Overall Log File for YOUR OWN PERL SCRIPT :
#It is necessary to create a overall LOG file of your script
#That can capture screen dump of messages
#That can capture screen dump of all the errors and warning.
use File::Tee qw(tee);
tee(STDOUT, '>', 'myPerlScript.log');
tee(STDERR, '>', 'myPerlScript.error.warn.log');
EDA Automation : Glob-ing in PERL :
Definition: The expansion of filename argument patterns into a list of matching filenames.
Here is the code snippet to perform glob-ing in PERL :
my @files = </home/docs/*.c>; # grabs list of files ending in .c | |
my @files = glob("/home/docs/*.c"); # same thing using glob operator | |
while (my $file = <abc*.html>) { | |
# output each .html file starting with abc | |
print "File: $file \n"; | |
} | |
foreach my $file (<abc*.html>) { | |
# output each .html file starting with abc | |
print "File: $file \n"; | |
} |
Unix Style File Operation in PERL :
Here are some PERL routines which can do file operations in UNIX/LINUX style which sitting inside the PERL code itself :
unlink("myfile.dat"); # removes myfile.dat
unlink <*.o>; # same as “rm *.o” in Unix.
rename("oldname", "newName"); # same as “mv oldname newName” in Unix. returns false if couldn’t rename
mkdir("datafiles", 0777) or warn "Cannot make datafiles directory: $!"; # create datafiles with world r/w/x permissions
rmdir("datafiles"); # deletes datafiles directory if it’s empty
chmod(0777, "myProg.pl"); # gives world r/w/x permissions to myProg.pl file
The Entire article is well narrated in the below video :