Professional Documents
Culture Documents
Opening a file
Before reading or writing to a file, we need to open it first.
This tells the operating system that we are currently accessing
the file and no one else can change it while we are working
with it.
open() is the built-in function used to open a file.
Syntax:
open(filevariable, filename)
“file variable”
“filevariable” is the name that we use in our Perl program to
refer the file.
It is the first argument in open().
To name file variables, the rules are:
1. They should begin with an alphabet.
2. Can contain a sequence of alphabets, digits and underscores.
3. It’s a convention in Perl to use file variables in upper case, in
order to differentiate them with ordinary variables.
File modes
Represents what is the purpose of opening a file.
3 different modes of file access are there:
1. Read mode
2. Write mode
3. Append mode
“read” is the default file access mode. It enables us to read file
contents, but won’t allow to write to it.
“write” mode allows us to write some contents to a file. If the
file is already existing, the contents are over written.
“append” mode appends the data to a file. The already existing
contents are safe.
If a file is opened in read mode, and if doesn’t exists, it leads to
an error.
If a file is opened in write mode, if it doesn’t exists, it will be
created new.
Ex:
open(MYFILE, ”emp.txt”);
open(MYFILE, “>emp.txt”);
open(MYFILE, “>>emp.txt”);
die()
When die() is used, program terminates immediately and prints
the message passed to die().
Ex:
die(“stop this now\n”);
Writing data to a file
Writing can be done after opening a file in ‘write’ or ‘append’
mode.
print() can be used to write data to a file.
Ex:
open(MYFILE, “>emp.txt”);
print MYFILE “This is line1\n”;
print MYFILE “this is line2\n”;
Ex: copy a file, merge two files
mkdir()
Creates a new directory in the specified path
mkdir(dirname)
chdir()
Sets a directory to be the current working directory.
chdir(dirname);
opendir()
Opens a directory i.e. allows us to examine the list of files and
subdirectories
opendir(dir_variable, dir name);
‘dir_variable’ is the variable name used by the program to
represent the directory.
‘dir name’ is the name of the directory.
Ex:
opendir(DIR1, “/home/murali/dir1”)
closedir()
Closes the specified directory.
closedir(dirvar);
Ex:
closedir(DIR1);
readdir()
Once a directory is opened, we can read every file and
subdirectory present in it.
readdir(dirvar);
Ex:
file=readdir(DIR1);
Or
print readdir(DIR1);
Reading directory contents into an array
@arr=readdir(D1);