You are on page 1of 18

File Operations

File Operations in Perl

 To work with Files in Perl, we need to use “open” and “close”


 Filehandle: a connection between our Perl program and the
operating system’s file structure.
 Contains information about the file, the way the file was
opened (read-only, etc), where you are in the file, and some
other attributes.
 Used without any special characters
 The convention is to use uppercase for filehandle variables to
avoid confusion with Perl keywords.
 Every file manipulation is done through filehandles

for internal use Copyright © Infineon Technologies AG 2014. All rights reserved. Page 2
Opening Files
 Syntax of “open” function:
open (filehandle, <MODE>, filename);

 Returns
 a nonzero value if the file has been opened successfully
 0 if an error has occurred
Default open mode: READ

if (open(BIGFILE, “datafile.dat”)){
statements to run
} else {
print “Cannot open the file!\n”;
}

for internal use Copyright © Infineon Technologies AG 2014. All rights reserved. Page 3
Closing Files

 Syntax of “close” function:

close filehandle;

 If you re-use already opened filehandle in another open


command, the first file is automatically closed and the filehandle
is opened with the new file
 Typical usage:

open(BIGFILE, “data.txt”;
statements…
close BIGFILE;

for internal use Copyright © Infineon Technologies AG 2014. All rights reserved. Page 4
Reading Files
 Simple way to read a file: ‘file input operator’ - a pair of angle
brackets around the filehandle
open(BIGFILE, “data.txt”)
Reads a line from the file data.txt
$line=<BIGFILE>; and store it in $line

 You can use loops to read an entire file


while (defined($line=<MFILE>)){
print $line;
}
 Short form: stores the line in the default variable “$_”
while (<MFILE>){
print $_;
}
 The shortform also checks for end-of-file for you
for internal use Copyright © Infineon Technologies AG 2014. All rights reserved. Page 5
Reading into Array

 You could read all lines from a file to an array as below:


open (MFILE, “data.txt”);
@list=<MFILE>; The entire file is read in ‘list’
close <MFILE>;

 Each line in the file is assigned as one element in the list


 The first line is @list[0], second in @[list[1], and so on
 Since the array or list is just a copy of the file’s contents, any
changes made to the array will not harm the original file

You can also run commands with Open : e.g. open(DATA, "ls -l |")

for internal use Copyright © Infineon Technologies AG 2014. All rights reserved. Page 6
Correct/Improve the Program

#!/usr/local/bin/perl # Program to open a file and print the contents

open (MYFILE, 'data.txt');

(<MYFILE>) {
print "$!\n";

close (MYFILE)

#!/usr/local/bin/perl # Program to open a file and print the contents


open (MYFILE, 'data.txt');
while (<MYFILE>) {
print "$_\n";
}
close (MYFILE);

for internal use Copyright © Infineon Technologies AG 2014. All rights reserved. Page 7
File Checks (use of die and warn)
 “die”: often used with file commands
 When die is encountered, the program stops executing and
shows a message such as:

died at fileopen.txt line 165


 Example on using die with open function: “open or die”
open(BIGFILE, “data.txt”) || die “Could not open file”;

 Any error recorded by Perl will be stored in a special variable ‘$!’


open(BIGFILE, “data.txt”) || die “Failed to open: $!”;

 “warn”: instead of exiting the program, you may simply issue a


warning
open(BIGFILE, “data.txt”) || warn “Warning: $!”;

for internal use Copyright © Infineon Technologies AG 2014. All rights reserved. Page 8
File Modes

Entities Definition
< Read Only Access
> Creates, Writes, and Truncates
>> Creates, Writes, and Appends
+< Reads and Writes
+> Reads, Writes, Creates and Truncates
+>> Reads, Writes, Creates and Appends

open(MYFILE, “>bigfile.txt”); # WRITE Mode


open(MYFILE, “>>bigfile.txt”); # APPEND Mode

for internal use Copyright © Infineon Technologies AG 2014. All rights reserved. Page 9
Writing Data to a File

 Writing data to a file: use print with the filehandle


print BIGDATA “Test Line”;

 You can use a logic structure to make sure a write has been
performed properly
if (! print MFILE $num1){
warn “Can’t write to the file!”;)
}
close (MFILE);

for internal use Copyright © Infineon Technologies AG 2014. All rights reserved. Page 10
Exercise (Copy file content)

#!/usr/bin/perl
# Open file to read
open(DATA1, "<file1.txt");
# Open new file to write
open(DATA2, ">file2.txt");
# Copy data from one file to another.
while(<DATA1>) {
print DATA2 $_;
}
close( DATA1 );
close( DATA2 );

Exercises/Chapter_06_File_Operations/File-Operations-1.pl
for internal use Copyright © Infineon Technologies AG 2014. All rights reserved. Page 11
File Tests
 Perl allows the UNIX like file tests to be performed

if (-r FILE) {..}

 The condition has one valid option followed by the


filehandle/filename to be tested
 Few basic tests are as below:
Test Description
-d true if directory
-e true if file exists
-f true if regular file
-r true if readable
-s returns size of file in bytes
-w true if writable
-z true if file exists but is empty
for internal use Copyright © Infineon Technologies AG 2014. All rights reserved. Page 12
Exercise (File Tests)

#/usr/bin/perl -w
my $file = "file1.txt";
my (@description, $size);
if (-e $file) {
push @description, 'a text file' if (-T $file);
push @description, 'a directory' if (-d $file);
push @description, 'executable' if (-x $file);
push @description, (($size = -s $file)) ? "$size bytes" :
'empty';
print "$file is ", join(', ',@description),"\n";
}

Exercises/Chapter_06_File_Operations/File-Operations-2.pl
for internal use Copyright © Infineon Technologies AG 2014. All rights reserved. Page 13
Misc File Operations

 To delete a file, use the unlink command with the filename:

unlink file1.dat;

 Reading Directories: use “opendir”

opendir handle directory;

here handle is the directory handle you want to open, and


directory is the name of the directory to be read.

for internal use Copyright © Infineon Technologies AG 2014. All rights reserved. Page 14
Misc File Operations (cont.)

 Read a directory: use “readdir”


 Close a directory: use “closedir”
opendir TEMPDIR, “./temp” || die;

$dir_entry=readdir TEMPDIR;

closedir TEMPDIR;

 Just like file reading, you can read a directory line by line or an
entire directory
# Read the entire directory
opendir (MDIR, “./temp”) || die;
@filelist=readdir MDIR;
closedir MDIR;

for internal use Copyright © Infineon Technologies AG 2014. All rights reserved. Page 15
Misc File Operations (cont.)

 To change directories, you can use the “chdir” command


 Changes in directory can be specified absolutely or relatively

chdir ../book;

 If you do not specify a directory argument for chdir, it will


change to your home directory
 To create a directory, use the mkdir command with both the new
directory name and the permissions are arguments

mkdir temp, 0755 || die;

for internal use Copyright © Infineon Technologies AG 2014. All rights reserved. Page 16
Do it yourself!

#!/usr/bin/perl –w
use strict;
my $file = "file.txt";
if (____) { # Check if File exists and is readable
# Open File for writing
print FILE "Created by Perl\n";
# Close the File
}

Exercises/Chapter_06_File_Operations/File-Operations-3.pl
for internal use Copyright © Infineon Technologies AG 2014. All rights reserved. Page 17

You might also like