Perl Programming - 03 Programming File

23
03-Perl Programming File 134 Danairat T. Line ID: Danairat FB: Danairat Thanabodithammachari +668-1559-1446

Transcript of Perl Programming - 03 Programming File

Page 1: Perl Programming - 03 Programming File

03- Perl Programming

File

134

Danairat T.

Line ID: Danairat

FB: Danairat Thanabodithammachari

+668-1559-1446

Page 2: Perl Programming - 03 Programming File

Danairat T.

Perl File Processing

• Perl works with file using a filehandle which is

a named internal Perl structure that associates

a physical file with a name.

135

Page 3: Perl Programming - 03 Programming File

Danairat T.

Files Processing - Topics

• Open and Close File

• Open File Options

• Read File

• Write File

• Append File

• Filehandle Examples

– Read file and write to another file

– Copy file

– Delete file

– Rename file

– File statistic

– Regular Expression and File processing

136

Page 4: Perl Programming - 03 Programming File

Danairat T.

Open, Read and Close File

137

• The open function takes a filename and creates a filehandle.

The file will be opened for reading only by default.

#!/usr/bin/perluse strict;use warnings;

my $myFile = "fileread.txt"; # the file “filetest.txt” must be existmy $myLine;if (open (MYFILEHANDLE, $myFile)) {

while ($myLine = <MYFILEHANDLE>) { # read linechomp($myLine); # trim whitespace at end of lineprint "$myLine \n";

}close (MYFILEHANDLE);

} else {print "File could not be opened. \n";

}exit(0);

OpenFileEx01.pl

Results:-

<print the file content>

Page 5: Perl Programming - 03 Programming File

Danairat T.

Open File Options

138

mode operand create

delete and recreate

file if file exists

read <

write > ✓ ✓

append >> ✓

read/write +<

read/write +> ✓ ✓

read/append +>> ✓

Page 6: Perl Programming - 03 Programming File

Danairat T.

Open File Options

139

• Using < for file reading.

#!/usr/bin/perluse strict;use warnings;

my $myFile = "fileread.txt"; # the file “filetest.txt” must be existmy $myLine;if (open (MYFILEHANDLE, '<' , $myFile)) { # using ‘<‘ and . for file read

while ($myLine = <MYFILEHANDLE>) { # read linechomp($myLine); # trim whitespace at end of lineprint "$myLine \n";

}close (MYFILEHANDLE);

} else {print "File could not be opened. \n";

}exit(0);

OpenFileReadEx01.pl

Results:-

<print the file content>

Page 7: Perl Programming - 03 Programming File

Danairat T.

Open File Options

140

• Using > for file writing to new file.

#!/usr/bin/perluse strict;use warnings;

my $myFile = "filewrite.txt"; my @myData = ("line1", "line2", "line3");

if (open (MYFILEHANDLE, '>' , $myFile)) {foreach my $myLine (@myData) {

print MYFILEHANDLE "$myLine \n"; # print to filehandle}close (MYFILEHANDLE);

} else {print "File could not be opened. \n";

}exit(0);

OpenFileWriteEx01.pl

Results:-

<see from the output file>

Page 8: Perl Programming - 03 Programming File

Danairat T.

Open File Options

141

• Using >> to append data to file. If the file does not exist then it is create a

new file.

#!/usr/bin/perluse strict;use warnings;

my $myFile = "filewrite.txt"; my @myData = ("line4", "line5", "line6");

if (open (MYFILEHANDLE, ‘>>' , $myFile)) {foreach my $myLine (@myData) {

print MYFILEHANDLE "$myLine \n"; # print to filehandle}close (MYFILEHANDLE);

} else {print "File could not be opened. \n";

}exit(0);

OpenFileAppendEx01.pl

Results:-

<see from the output file>

Page 9: Perl Programming - 03 Programming File

Danairat T.

File Locking

• Lock File for Reading (shared lock): Allow other to

open the file but no one can modify the file

• Lock File for Writing (exclusive lock): NOT allow

anyone to open the file either for reading or for

writing

• Unlock file is activated when close the file

142

Shared lock: 1

Exclusive lock: 2

Unlock: 8

Page 10: Perl Programming - 03 Programming File

Danairat T.

File Locking – Exclusive Locking

143

#!/usr/bin/perluse strict;use warnings;use Fcntl;

my $file = 'testfile.txt';

# open the fileopen (FILE, ">>", "$file") || die "problem opening $file\n";

# immediately lock the fileflock (FILE, 2);

# test keeping the lock on the file for ~20 secondsmy $count = 0;while ($count++ < 30){print "count = $count\n";print FILE "count = $count\n";sleep 1;}

# close the file, which also removes the lockclose (FILE);

exit(0);

FileExLockEx01.pl

Please run this concurrence

with FileExLockEx02.pl, see

next page.

Results:-

<see from the output file>

Page 11: Perl Programming - 03 Programming File

Danairat T.

File Locking – Exclusive Locking

144

#!/usr/bin/perluse strict;use warnings;use Fcntl;

my $file = 'testfile.txt';

# open the fileopen (FILE, ">>", "$file") || die "problem opening $file\n";

# immediately lock the fileflock (FILE, 2);

# test keeping the lock on the file for ~20 secondsmy $count = 0;while ($count++ < 30){print "count : $count\n";print FILE "count : $count\n";sleep 1;}

# close the file, which also removes the lockclose (FILE);

exit(0);

FileExLockEx02.pl

Please run this concurrency

with FileExLockEx01.pl

Results:-

<see from the output file>

Page 12: Perl Programming - 03 Programming File

Danairat T.

File Locking – Shared Locking

145

#!/usr/bin/perluse strict;use warnings;use Fcntl;

my $file = 'testfile.txt';

# open the fileopen (FILE, "<", "$file") || die "problem opening $file\n";

# immediately lock the fileflock (FILE, 1);

# test keeping the lock on the file for ~20 secondsmy $count = 0;while ($count++ < 30){

print "Shared Locking\n";sleep 1;}

# close the file, which also removes the lockclose (FILE);

exit(0);

FileShLockEx01.pl

Please run this concurrency

with FileExLockEx02.pl

Results:-

<see from the output file>

Page 13: Perl Programming - 03 Programming File

Danairat T.

Filehandle Examples

146

• Read file and write to another file

#!/usr/bin/perluse strict;use warnings;

my $myFileRead = "fileread.txt"; my $myFileWrite = "filewrite.txt";

if (open (MYFILEREAD, '<' , $myFileRead)) { # using ‘<‘ and . for file readif (open (MYFILEWRITE, '>' , $myFileWrite)) {

while (my $myLine = <MYFILEREAD>) { # read linechomp($myLine); # trim whitespace at end of lineprint MYFILEWRITE "$myLine\n";

}close (MYFILEWRITE);

} else {print "File $myFileWrite could not be opened. \n";}close (MYFILEREAD);

} else {print "File $myFileRead could not be opened. \n";}exit(0);

ReadFileWriteFile01.pl

Results:-

<Please see output file>

Page 14: Perl Programming - 03 Programming File

Danairat T.

Filehandle Examples

147

• Copy File using module File::Copy

#!/usr/bin/perluse strict;use warnings;use File::Copy;

my $myFileRead = "fileread.txt"; my $myFileWrite = "filewrite.txt";

if (copy ($myFileRead, $myFileWrite)) {print "success copy from $myFileRead to $myFileWrite\n“;

}exit(0);

CopyEx01.pl

Results:-

success copy from fileread.txt to filewrite.txt

Page 15: Perl Programming - 03 Programming File

Danairat T.

Filehandle Examples

148

• Delete file using unlink

– unlink $file : To remove only one file

– unlink @files : To remove the files from list

– unlink <*.old> : To remove all files .old in current dir

#!/usr/bin/perluse strict;use warnings;

my $myPath = "./mypath/";my $myFileWrite = "filewrite.txt";

if (unlink ("$myPath$myFileWrite")) {print "Success remove ${myPath}${myFileWrite}\n";

} else {print "Unsuccess remove ${myPath}${myFileWrite}\n"

}exit(0);

FileRemoveEx01.pl

Results:-

Success remove ./mypath/filewrite.txt

Page 16: Perl Programming - 03 Programming File

Danairat T.

Filehandle Examples

149

• Create directory and move with rename the file

#!/usr/bin/perluse strict;use warnings;use File::Copy;use File::Path;

my $myFileRead = "fileread.txt"; my $myPath = "./mypath/";my $myFileWrite = "filewrite.txt";exit (0) unless (mkpath($myPath));if (move ($myFileRead, "$myPath$myFileWrite")) {

print "Success move from $myFileRead to $myFileWrite\n";} else {

print "Unsuccess move from $myFileRead to ${myPath}${myFileWrite}\n"}exit(0);

FileMoveEx01.pl

Results:-

Success move from fileread.txt to ./mypath/filewrite.txt

Page 17: Perl Programming - 03 Programming File

Danairat T.

Filehandle Examples

150

• Read file to array at one time

#!/usr/bin/perluse strict;use warnings;

my $myFile = "fileread.txt"; exit (0) unless ( open (MYFILEHANDLE, '<' , $myFile) );my @myLines = <MYFILEHANDLE>;close (MYFILEHANDLE);

foreach my ${myLine} (@myLines) {chomp($myLine);print $myLine . "\n";

}exit(0);

ReadFileToArrayEx01.pl

Results:-

<The fileread.txt print to screen>

Page 18: Perl Programming - 03 Programming File

Danairat T.

Test File

151

• -e is the file exists.

• -T is the file a text file

• -r is the file readable

#!/usr/bin/perluse strict;use warnings;

my $myFile = "fileread.txt"; if (-r $myFile) {

print "The file is readable \n";} else {print "File does not exist. \n";

}exit(0);

FileTestEx01.pl

Results:-

The file is readable

• -d Is the file a directory

• -w Is the file writable

• -x Is the file executable

Page 19: Perl Programming - 03 Programming File

Danairat T.

File stat()

152

• File statistic using stat();

$dev - the file system device number$ino - inode number$mode - mode of file$nlink - counts number of links to file$uid - the ID of the file's owner$gid - the group ID of the file's owner$rdev - the device identifier$size - file size in bytes$atime - last access time$mtime - last modification time$ctime - last change of the mode$blksize - block size of file$blocks - number of blocks in a file

my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks) = stat($file);

Page 20: Perl Programming - 03 Programming File

Danairat T.

File stat()

153

• File statistic using stat();

#!/usr/bin/perluse strict;use warnings;

my $myFile = "fileread.txt"; if (-e $myFile) {

my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks) = stat($myFile);

print "\$size is $size bytes \n";print scalar localtime($mtime) . "\n";

} else {print "File does not exist. \n";

}exit(0);

FileStatEx01.pl

Results:-

$size is 425 bytes

Tue Nov 10 21:39:07 2009

Page 21: Perl Programming - 03 Programming File

Danairat T.

File and Regular Expression

154

• Reading the configuration file

param1=value1

param2=value2param3=value3

config.conf

Page 22: Perl Programming - 03 Programming File

Danairat T.

File and Regular Expression

155

• Reading the configuration file

#!/usr/bin/perluse strict;use warnings;my $myConfigFile = "config.conf";my %configHash = ();exit (0) unless ( open (MYCONFIG, '<' , $myConfigFile) );while (<MYCONFIG>) {

chomp; # no newlines/#.*//; # no commentss/^\s+//; # no leading whites/\s+$//; # no trailing whitenext unless length; # anything left?my ($myParam, $myValue) = split(/\s*=\s*/, $_, 2);$configHash{$myParam} = $myValue;

}close (MYCONFIG);foreach my $myKey (keys %configHash) {

print "$myKey contains $configHash{$myKey}\n";}exit(0);

ConfigFileReadEx01.pl

Results:-

param2 contains value2

param3 contains value3

param1 contains value1

Page 23: Perl Programming - 03 Programming File

Danairat T.

Line ID: Danairat

FB: Danairat Thanabodithammachari

+668-1559-1446

Thank you