Directory & File Handling

                                                                                                                         

 

File Handle:

  • A handle is a variable that acts as a reference between your Perl program and the operating system’s file /directory structure.
  • File/Directory handles contain information about the file, the way the file was opened (read-only, etc), where you are in the file, and some other attributes.
  • Every File/Directory manipulation in Perl is done through file handles.
  • File/Directory handle variables do not have a special character in front of them like scalars, lists, arrays, or hashes.

 

STD Handle:

  • In an effort to make programs more uniform, there are three connections that always exist when your program starts.
  • These are STDIN, STDOUT, and STDERR. Actually, these names are file handles.
  • File handles are variables used to manipulate files.
  • The three special file handles are always open STDIN, STDOUT and STDERR.
  • STDIN reads from standard input which is usually the keyboard in normal Perl script or input from a Browser in a CGI script.
  • STDOUT (Standard Output) and STDERR (Standard Error)by default write to a console or a browser in CGI.

 

File Handle:

Example: Using STDIN

  • Reading a line of input from the standard input, STDIN, is one of the easiest things that you can do in Perl.

while (<STDIN>) {

    print();

}

Note :

  • The <> characters, when used together, are called the DIAMOND operator. It tells Perl to read a line of input from the file handle inside the operator.

while ($inputLine = <STDIN>) {

     print($inputLine);

}

  • Using the Diamond Operator (<>) :    If no file handle is used with the diamond operator, Perl will examine the @ARGV special variable. If @ARGV has no elements, then the diamond operator will read from STDIN-either from the keyboard or from a redirected file.
  • So, if you wanted to display the contents of more than one file, you could use the program shown below:

while (<>) {

    print();

}

Directory Handling:

Perl has several functions to operate on functions the opendir(), readdir() and closedir() functions are a common way to achieve this.

  • opendir (DIR_HANDLE,”directory”) returns a Directory HANDLE — just an identifier (no $) — for a given directory to be opened for reading.
  • readdir (DIR_HANDLE) returns a scalar (string) of the BASENAME of the file (no sub directories (: or /))
  • closedir (DIR_HANDLE) simply closes the directory.

 

Creating Directory :

  • To create a directory, use the mkdir command with both the new directory name and the permissions are arguments:

mkdir newdir, perms;

Example:

mkdir sachin, 0755;

#will create the directory temp under the current directory with the UNIX permissions 755

 

Reading Directory :

opendir(DIR,”./Internet”) || die “NO SUCH Directory: Images”; while ($file = readdir(DIR) )

{

print ” $file\n”;

}

closedir(DIR);

 

Deleting Directory :

To remove a directory, use the rmdir command with the directory name.

  • One can only remove empty directory .

Example:

                rmdir sachin;

Changing Directory:

  • To change directories, you can use the chdir command. Changes in directory can be specified absolutely or relatively.

Example:

chdir ../perl;

#will move up one directory level and down into the directory book.

 

File Handling

File Opening:

  • To open a file use the open function with a file handle.

Syntax:

open handle, filename;

  • where handle is the file handle and filename is the file to be opened, which may include a path.

Example1 : From Current directory

open (DATA, “file1.txt”);

Example2 : From secondary directory

open(DATA, “d:\sachin\file1.txt”);

 

Checking an open:

  • Use open function inside an if statement to make sure the file was opened properly. Otherwise, commands later in the program would cause errors.

if (open(DATA, “file.txt”)) {

      statements to run

}

else {

      print “Cannot open the file!\n”;

      exit 0;

}

Closing a file handle : After Processing your file ,Close file handle.

open (DATA, “file1.txt”);

{processing; }

close DATA;

 

Reusing a file handle:

  • If you have one file open with a specific file handle, and then use the same file handle in another open command, the first file is automatically closed and the file handle is opened with the new file.
  • This can be used to eliminate the opening and closing of file statements in a program, as long as the files are used sequentially

 

Modes to process the file:

Entities Definition
< or r Read Only Access
> or w Creates, Writes, and Truncates
>> or a Writes, Appends, and Creates
+< or r+ Reads and Writes
+> or w+ Read, Writes, Creates, and Truncate
+>> or a+ Reads, Writes, Appends , and create

 

Reading from a file handle:

Syntax: open(DATA, “<file.txt”);

  • Here less than < sign indicates that file has to be opened in read-only mode
  • Here DATA is the file handle which will be used to read the file.
  • Here is the example which will open a file and will print its content over the screen.

Example:

#!/usr/bin/perl

open(DATA, “<file.txt”);

while(<DATA>) {

     print “$_”;

}

 

Writing & appending data in file from a file handle:

  • A double >> opens the file for appending, placing the file pointer at the end, so that you can immediately start appending information.
  • However, you cannot read from it unless you have placed a plus sign in front of it:

Syntax :

open(DATA,”+>>file.txt”) || die “Couldn’t open file file.txt, $!”;

Example:

$my=“I was staying in hotel radisson”;

open (DAT,”+>>file.txt”);

print DAT “$my”;

close(DAT);

 

Copying Files:

  • Here is the example which opens an existing file file1.txt and read it line by line and generate another copy file2.txt

Example:

#!/usr/bin/perl

open(DATA1, “<file1.txt”);          # Open file to read

open(DATA2, “>file2.txt”);          # Open new file to write

while(<DATA1>) {
print DATA2 $_;                       # Copy data from one file to another.
}
close( DATA1 );
close( DATA2 );

 

Renaming a file:

  • Here is an example which shows how we can rename a file file1.txt to file2.txt. Assuming file is available in /usr/test directory.

Example:

#!/usr/bin/perl

rename (“/usr/test/file1.txt”, “/usr/test/file2.txt” );

  • This function rename takes two arguments and it just rename existing file .

 

Deleting an exiting file:

  • To delete a file file1.txt using unlink function.

#!/usr/bin/perl

unlink (“/usr/test/file1.txt”);

 

Working with Multiple files:

  • At the same time you can work on multiple files.
  • Multiple file can opened in same mode or may be opened in different mode.

Example:

One file can be opened in read mode and other can be opened in write mode.

 

Working with Binary files:

For writing binary data to a file you don’t want PERL to convert anything, so you have to use the the binmode command with the filehandle to tell Perl this is to be written literally:

open(BDATA, “>file1.dat”);

binmode (BDATA);

  • You only need to specify binmode for a filehandle once, until you close the file
  • On some operating systems (UNIX/Linux and Macintosh) binmode is ignored as there is no distinction between binary and text files

 

File Test:

  • Perl allows the UNIX file tests to be performed. We can perform by using conditional statements:

Example:

if (-r FILE) {..}

  • The condition has one valid option followed by the file handle to be tested.
  • If file is out of current directory , you can use a filename or full path and filename instead of a file handle.

 

Test List:

symbol Explanation
-B true if a binary file
-d true if directory
-e true if file exists
-r true if readable
-w true if writable
-T true if text file
-z true if file exists but is empty

                                                                                                                         

 

Leave a Reply

Your email address will not be published. Required fields are marked *