This document discusses file and directory manipulation in Perl, including opening, reading from, and writing to files, as well as common file test operators. It also covers opening, reading from, and closing directories, rewinding the directory pointer, and changing, creating, and deleting directories.
2. Opening a File
To read from a file, must use a file handle.
by convention, all caps
open a file (for reading):
open FILE, myfile.txt;
open file for writing:
open OUTFILE, >output.txt;
open file for appending:
open APPFILE, >>append.txt;
3. Reading from a file
open FILE, myfile.txt;
$one_line = <FILE>;
@all_lines = <FILE>;
@all_lines get all remaining lines from
myfile.txt
puts each line of file into one member of array
remember chomp!
4. printing to a file
open OUTFILE, >output.txt;
print OUTFILE, Hello World!n;
this can be tedious if all outputs are to same
output file.
select OUTFILE;
make OUTFILE the default file handle for all print
statements.
5. Close your files!
open FILE, myfile.txt;
@all_lines = <FILE>;
close FILE;
opening another file to the same filehandle
will implicitly close the first one.
dont rely on this. Its not Good Programming
Practice.
6. File Test Operators
Test to see if something is true about a file
full list on page 98 of Prog. Perl.
if (-e myfile.txt){
print file exists, now openingn;
open FILE, myfile.txt;
}
can operate on filename or already existing
filehandle
7. Directory manipulation
directories can be opened, read, created,
deleted, much like files.
take care when doing these operations:
youre affecting your directory structure
many of the functions success will depend
on what permissions you have on the
specified directories.
8. open, read, close
opendir DIR public_html;
$nextfile = readdir DIR;
@remaining_files = readdir DIR;
closedir DIR;
10. Change, Create, and Delete
chdir change working directory.
mkdir create directory (like unix call)
rmdir remove directory (like unix call)
works if and only if directory is empty
chdir public_html;
mkdir images
rmdir temp;