SlideShare a Scribd company logo
03- Perl Programming
File
134
Danairat T.
Line ID: Danairat
FB: Danairat Thanabodithammachari
+668-1559-1446
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
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
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/perl
use strict;
use warnings;
my $myFile = "fileread.txt"; # the file โ€œfiletest.txtโ€ must be exist
my $myLine;
if (open (MYFILEHANDLE, $myFile)) {
while ($myLine = <MYFILEHANDLE>) { # read line
chomp($myLine); # trim whitespace at end of line
print "$myLine n";
}
close (MYFILEHANDLE);
} else {
print "File could not be opened. n";
}
exit(0);
OpenFileEx01.pl
Results:-
<print the file content>
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 +>> โœ“
Danairat T.
Open File Options
139
โ€ข Using < for file reading.
#!/usr/bin/perl
use strict;
use warnings;
my $myFile = "fileread.txt"; # the file โ€œfiletest.txtโ€ must be exist
my $myLine;
if (open (MYFILEHANDLE, '<' , $myFile)) { # using โ€˜<โ€˜ and . for file read
while ($myLine = <MYFILEHANDLE>) { # read line
chomp($myLine); # trim whitespace at end of line
print "$myLine n";
}
close (MYFILEHANDLE);
} else {
print "File could not be opened. n";
}
exit(0);
OpenFileReadEx01.pl
Results:-
<print the file content>
Danairat T.
Open File Options
140
โ€ข Using > for file writing to new file.
#!/usr/bin/perl
use 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>
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/perl
use 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>
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
Danairat T.
File Locking โ€“ Exclusive Locking
143
#!/usr/bin/perl
use strict;
use warnings;
use Fcntl;
my $file = 'testfile.txt';
# open the file
open (FILE, ">>", "$file") || die "problem opening $filen";
# immediately lock the file
flock (FILE, 2);
# test keeping the lock on the file for ~20 seconds
my $count = 0;
while ($count++ < 30)
{
print "count = $countn";
print FILE "count = $countn";
sleep 1;
}
# close the file, which also removes the lock
close (FILE);
exit(0);
FileExLockEx01.pl
Please run this concurrence
with FileExLockEx02.pl, see
next page.
Results:-
<see from the output file>
Danairat T.
File Locking โ€“ Exclusive Locking
144
#!/usr/bin/perl
use strict;
use warnings;
use Fcntl;
my $file = 'testfile.txt';
# open the file
open (FILE, ">>", "$file") || die "problem opening $filen";
# immediately lock the file
flock (FILE, 2);
# test keeping the lock on the file for ~20 seconds
my $count = 0;
while ($count++ < 30)
{
print "count : $countn";
print FILE "count : $countn";
sleep 1;
}
# close the file, which also removes the lock
close (FILE);
exit(0);
FileExLockEx02.pl
Please run this concurrency
with FileExLockEx01.pl
Results:-
<see from the output file>
Danairat T.
File Locking โ€“ Shared Locking
145
#!/usr/bin/perl
use strict;
use warnings;
use Fcntl;
my $file = 'testfile.txt';
# open the file
open (FILE, "<", "$file") || die "problem opening $filen";
# immediately lock the file
flock (FILE, 1);
# test keeping the lock on the file for ~20 seconds
my $count = 0;
while ($count++ < 30)
{
print "Shared Lockingn";
sleep 1;
}
# close the file, which also removes the lock
close (FILE);
exit(0);
FileShLockEx01.pl
Please run this concurrency
with FileExLockEx02.pl
Results:-
<see from the output file>
Danairat T.
Filehandle Examples
146
โ€ข Read file and write to another file
#!/usr/bin/perl
use strict;
use warnings;
my $myFileRead = "fileread.txt";
my $myFileWrite = "filewrite.txt";
if (open (MYFILEREAD, '<' , $myFileRead)) { # using โ€˜<โ€˜ and . for file read
if (open (MYFILEWRITE, '>' , $myFileWrite)) {
while (my $myLine = <MYFILEREAD>) { # read line
chomp($myLine); # trim whitespace at end of line
print MYFILEWRITE "$myLinen";
}
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>
Danairat T.
Filehandle Examples
147
โ€ข Copy File using module File::Copy
#!/usr/bin/perl
use strict;
use warnings;
use File::Copy;
my $myFileRead = "fileread.txt";
my $myFileWrite = "filewrite.txt";
if (copy ($myFileRead, $myFileWrite)) {
print "success copy from $myFileRead to $myFileWritenโ€œ;
}
exit(0);
CopyEx01.pl
Results:-
success copy from fileread.txt to filewrite.txt
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/perl
use 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
Danairat T.
Filehandle Examples
149
โ€ข Create directory and move with rename the file
#!/usr/bin/perl
use 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 $myFileWriten";
} else {
print "Unsuccess move from $myFileRead to
${myPath}${myFileWrite}n"
}
exit(0);
FileMoveEx01.pl
Results:-
Success move from fileread.txt to ./mypath/filewrite.txt
Danairat T.
Filehandle Examples
150
โ€ข Read file to array at one time
#!/usr/bin/perl
use 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>
Danairat T.
Test File
151
โ€ข -e is the file exists.
โ€ข -T is the file a text file
โ€ข -r is the file readable
#!/usr/bin/perl
use 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
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);
Danairat T.
File stat()
153
โ€ข File statistic using stat();
#!/usr/bin/perl
use 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
Danairat T.
File and Regular Expression
154
โ€ข Reading the configuration file
param1=value1
param2=value2
param3=value3
config.conf
Danairat T.
File and Regular Expression
155
โ€ข Reading the configuration file
#!/usr/bin/perl
use strict;
use warnings;
my $myConfigFile = "config.conf";
my %configHash = ();
exit (0) unless ( open (MYCONFIG, '<' , $myConfigFile) );
while (<MYCONFIG>) {
chomp; # no newline
s/#.*//; # no comments
s/^s+//; # no leading white
s/s+$//; # no trailing white
next 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
Danairat T.
Line ID: Danairat
FB: Danairat Thanabodithammachari
+668-1559-1446
Thank you
Ad

Recommended

PDF
Perl for System Automation - 01 Advanced File Processing
Danairat Thanabodithammachari
ย 
PDF
Perl Programming - 04 Programming Database
Danairat Thanabodithammachari
ย 
PDF
Perl Programming - 01 Basic Perl
Danairat Thanabodithammachari
ย 
PPTX
Hadoop 20111117
exsuns
ย 
PPTX
Introduction to-linux
kishore1986
ย 
PPTX
Hadoop 20111215
exsuns
ย 
PDF
Course 102: Lecture 8: Composite Commands
Ahmed El-Arabawy
ย 
PDF
Course 102: Lecture 7: Simple Utilities
Ahmed El-Arabawy
ย 
PPTX
Linux networking
Arie Bregman
ย 
PPTX
2015 bioinformatics python_io_wim_vancriekinge
Prof. Wim Van Criekinge
ย 
PPTX
Linux administration training
iman darabi
ย 
PDF
Course 102: Lecture 6: Seeking Help
Ahmed El-Arabawy
ย 
PPTX
Hive data migration (export/import)
Bopyo Hong
ย 
PPTX
Linux Fundamentals
DianaWhitney4
ย 
PPTX
Ansible for Beginners
Arie Bregman
ย 
PDF
Course 102: Lecture 3: Basic Concepts And Commands
Ahmed El-Arabawy
ย 
PPTX
(Practical) linux 104
Arie Bregman
ย 
ODP
Sahul
sahul azzez m.i
ย 
PPTX
(Practical) linux 101
Arie Bregman
ย 
PDF
Centralized + Unified Logging
Gabor Kozma
ย 
PDF
Tajo Seoul Meetup-201501
Jinho Kim
ย 
PPTX
Linux Shell Basics
Constantine Nosovsky
ย 
PDF
Linux Network commands
Hanan Nmr
ย 
PDF
Linux basic for CADD biologist
Ajay Murali
ย 
PPTX
Unix - Filters/Editors
ananthimurugesan
ย 
PDF
Course 102: Lecture 12: Basic Text Handling
Ahmed El-Arabawy
ย 
PDF
linux-commandline-magic-Joomla-World-Conference-2014
Peter Martin
ย 
PDF
JEE Programming - 03 Model View Controller
Danairat Thanabodithammachari
ย 
PDF
Setting up Hadoop YARN Clustering
Danairat Thanabodithammachari
ย 

More Related Content

What's hot (20)

PPTX
Linux networking
Arie Bregman
ย 
PPTX
2015 bioinformatics python_io_wim_vancriekinge
Prof. Wim Van Criekinge
ย 
PPTX
Linux administration training
iman darabi
ย 
PDF
Course 102: Lecture 6: Seeking Help
Ahmed El-Arabawy
ย 
PPTX
Hive data migration (export/import)
Bopyo Hong
ย 
PPTX
Linux Fundamentals
DianaWhitney4
ย 
PPTX
Ansible for Beginners
Arie Bregman
ย 
PDF
Course 102: Lecture 3: Basic Concepts And Commands
Ahmed El-Arabawy
ย 
PPTX
(Practical) linux 104
Arie Bregman
ย 
ODP
Sahul
sahul azzez m.i
ย 
PPTX
(Practical) linux 101
Arie Bregman
ย 
PDF
Centralized + Unified Logging
Gabor Kozma
ย 
PDF
Tajo Seoul Meetup-201501
Jinho Kim
ย 
PPTX
Linux Shell Basics
Constantine Nosovsky
ย 
PDF
Linux Network commands
Hanan Nmr
ย 
PDF
Linux basic for CADD biologist
Ajay Murali
ย 
PPTX
Unix - Filters/Editors
ananthimurugesan
ย 
PDF
Course 102: Lecture 12: Basic Text Handling
Ahmed El-Arabawy
ย 
PDF
linux-commandline-magic-Joomla-World-Conference-2014
Peter Martin
ย 
Linux networking
Arie Bregman
ย 
2015 bioinformatics python_io_wim_vancriekinge
Prof. Wim Van Criekinge
ย 
Linux administration training
iman darabi
ย 
Course 102: Lecture 6: Seeking Help
Ahmed El-Arabawy
ย 
Hive data migration (export/import)
Bopyo Hong
ย 
Linux Fundamentals
DianaWhitney4
ย 
Ansible for Beginners
Arie Bregman
ย 
Course 102: Lecture 3: Basic Concepts And Commands
Ahmed El-Arabawy
ย 
(Practical) linux 104
Arie Bregman
ย 
Sahul
sahul azzez m.i
ย 
(Practical) linux 101
Arie Bregman
ย 
Centralized + Unified Logging
Gabor Kozma
ย 
Tajo Seoul Meetup-201501
Jinho Kim
ย 
Linux Shell Basics
Constantine Nosovsky
ย 
Linux Network commands
Hanan Nmr
ย 
Linux basic for CADD biologist
Ajay Murali
ย 
Unix - Filters/Editors
ananthimurugesan
ย 
Course 102: Lecture 12: Basic Text Handling
Ahmed El-Arabawy
ย 
linux-commandline-magic-Joomla-World-Conference-2014
Peter Martin
ย 

Viewers also liked (15)

PDF
JEE Programming - 03 Model View Controller
Danairat Thanabodithammachari
ย 
PDF
Setting up Hadoop YARN Clustering
Danairat Thanabodithammachari
ย 
PDF
Big data Hadoop Analytic and Data warehouse comparison guide
Danairat Thanabodithammachari
ย 
PDF
Digital Transformation, Enterprise Architecture, Big Data by Danairat
Danairat Thanabodithammachari
ย 
PDF
Perl Programming - 02 Regular Expression
Danairat Thanabodithammachari
ย 
PDF
The Business value of agile development
Phavadol Srisarnsakul
ย 
PDF
JEE Programming - 05 JSP
Danairat Thanabodithammachari
ย 
PDF
JEE Programming - 06 Web Application Deployment
Danairat Thanabodithammachari
ย 
PDF
Glassfish JEE Server Administration - The Enterprise Server
Danairat Thanabodithammachari
ย 
PDF
IBM Cognos Analytics: Empowering business by infusing intelligence across the...
IBM Analytics
ย 
PDF
JEE Programming - 02 The Containers
Danairat Thanabodithammachari
ย 
PDF
A Guide to IT Consulting- Business.com
Business.com
ย 
PDF
JEE Programming - 01 Introduction
Danairat Thanabodithammachari
ย 
PDF
The Face of the New Enterprise
Silicon Valley Bank
ย 
PDF
JEE Programming - 08 Enterprise Application Deployment
Danairat Thanabodithammachari
ย 
JEE Programming - 03 Model View Controller
Danairat Thanabodithammachari
ย 
Setting up Hadoop YARN Clustering
Danairat Thanabodithammachari
ย 
Big data Hadoop Analytic and Data warehouse comparison guide
Danairat Thanabodithammachari
ย 
Digital Transformation, Enterprise Architecture, Big Data by Danairat
Danairat Thanabodithammachari
ย 
Perl Programming - 02 Regular Expression
Danairat Thanabodithammachari
ย 
The Business value of agile development
Phavadol Srisarnsakul
ย 
JEE Programming - 05 JSP
Danairat Thanabodithammachari
ย 
JEE Programming - 06 Web Application Deployment
Danairat Thanabodithammachari
ย 
Glassfish JEE Server Administration - The Enterprise Server
Danairat Thanabodithammachari
ย 
IBM Cognos Analytics: Empowering business by infusing intelligence across the...
IBM Analytics
ย 
JEE Programming - 02 The Containers
Danairat Thanabodithammachari
ย 
A Guide to IT Consulting- Business.com
Business.com
ย 
JEE Programming - 01 Introduction
Danairat Thanabodithammachari
ย 
The Face of the New Enterprise
Silicon Valley Bank
ย 
JEE Programming - 08 Enterprise Application Deployment
Danairat Thanabodithammachari
ย 
Ad

Similar to Perl Programming - 03 Programming File (20)

PPTX
Bioinformatics p4-io v2013-wim_vancriekinge
Prof. Wim Van Criekinge
ย 
PDF
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
Bhavsingh Maloth
ย 
PPTX
Pattern matching &amp; file input and output
Mehul Jariwala
ย 
PPT
Bioinformatica 27-10-2011-p4-files
Prof. Wim Van Criekinge
ย 
PPTX
File handle in PROGRAMMable extensible interpreted .pptx
urvashipundir04
ย 
PDF
Introduction to writing readable and maintainable Perl
Alex Balhatchet
ย 
PPTX
Lecture 3 Perl & FreeBSD administration
Mohammed Farrag
ย 
PPT
File io
Pri Dhaka
ย 
PDF
Perl_Part3
Frank Booth
ย 
PPT
Perl Basics for Pentesters Part 1
n|u - The Open Security Community
ย 
PDF
PerlScripting
Aureliano Bombarely
ย 
PPTX
Perl basics for Pentesters
Sanjeev Kumar Jaiswal
ย 
PDF
Unit VI
Bhavsingh Maloth
ย 
PDF
Perl Fitxers i Directoris
frankiejol
ย 
PPT
Perl Intro 8 File Handles
Shaun Griffith
ย 
PPT
Bioinformatica 29-09-2011-p1-introduction
Prof. Wim Van Criekinge
ย 
PPTX
Bioinformatica p4-io
Prof. Wim Van Criekinge
ย 
ODP
The Essential Perl Hacker's Toolkit
Stephen Scaffidi
ย 
PPT
Unix Programming with Perl
Kazuho Oku
ย 
Bioinformatics p4-io v2013-wim_vancriekinge
Prof. Wim Van Criekinge
ย 
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
Bhavsingh Maloth
ย 
Pattern matching &amp; file input and output
Mehul Jariwala
ย 
Bioinformatica 27-10-2011-p4-files
Prof. Wim Van Criekinge
ย 
File handle in PROGRAMMable extensible interpreted .pptx
urvashipundir04
ย 
Introduction to writing readable and maintainable Perl
Alex Balhatchet
ย 
Lecture 3 Perl & FreeBSD administration
Mohammed Farrag
ย 
File io
Pri Dhaka
ย 
Perl_Part3
Frank Booth
ย 
Perl Basics for Pentesters Part 1
n|u - The Open Security Community
ย 
PerlScripting
Aureliano Bombarely
ย 
Perl basics for Pentesters
Sanjeev Kumar Jaiswal
ย 
Unit VI
Bhavsingh Maloth
ย 
Perl Fitxers i Directoris
frankiejol
ย 
Perl Intro 8 File Handles
Shaun Griffith
ย 
Bioinformatica 29-09-2011-p1-introduction
Prof. Wim Van Criekinge
ย 
Bioinformatica p4-io
Prof. Wim Van Criekinge
ย 
The Essential Perl Hacker's Toolkit
Stephen Scaffidi
ย 
Unix Programming with Perl
Kazuho Oku
ย 
Ad

More from Danairat Thanabodithammachari (16)

PDF
Thailand State Enterprise - Business Architecture and SE-AM
Danairat Thanabodithammachari
ย 
PDF
Agile Management
Danairat Thanabodithammachari
ย 
PDF
Agile Organization and Enterprise Architecture v1129 Danairat
Danairat Thanabodithammachari
ย 
PDF
Blockchain for Management
Danairat Thanabodithammachari
ย 
PDF
Enterprise Architecture and Agile Organization Management v1076 Danairat
Danairat Thanabodithammachari
ย 
PDF
Agile Enterprise Architecture - Danairat
Danairat Thanabodithammachari
ย 
PDF
Big data hadooop analytic and data warehouse comparison guide
Danairat Thanabodithammachari
ย 
PDF
JEE Programming - 04 Java Servlets
Danairat Thanabodithammachari
ย 
PDF
JEE Programming - 07 EJB Programming
Danairat Thanabodithammachari
ย 
PDF
Glassfish JEE Server Administration - JEE Introduction
Danairat Thanabodithammachari
ย 
PDF
Glassfish JEE Server Administration - Clustering
Danairat Thanabodithammachari
ย 
PDF
Glassfish JEE Server Administration - Module 4 Load Balancer
Danairat Thanabodithammachari
ย 
PDF
Java Programming - 07 java networking
Danairat Thanabodithammachari
ย 
PDF
Java Programming - 08 java threading
Danairat Thanabodithammachari
ย 
PDF
Java Programming - 06 java file io
Danairat Thanabodithammachari
ย 
PDF
Java Programming - 05 access control in java
Danairat Thanabodithammachari
ย 
Thailand State Enterprise - Business Architecture and SE-AM
Danairat Thanabodithammachari
ย 
Agile Management
Danairat Thanabodithammachari
ย 
Agile Organization and Enterprise Architecture v1129 Danairat
Danairat Thanabodithammachari
ย 
Blockchain for Management
Danairat Thanabodithammachari
ย 
Enterprise Architecture and Agile Organization Management v1076 Danairat
Danairat Thanabodithammachari
ย 
Agile Enterprise Architecture - Danairat
Danairat Thanabodithammachari
ย 
Big data hadooop analytic and data warehouse comparison guide
Danairat Thanabodithammachari
ย 
JEE Programming - 04 Java Servlets
Danairat Thanabodithammachari
ย 
JEE Programming - 07 EJB Programming
Danairat Thanabodithammachari
ย 
Glassfish JEE Server Administration - JEE Introduction
Danairat Thanabodithammachari
ย 
Glassfish JEE Server Administration - Clustering
Danairat Thanabodithammachari
ย 
Glassfish JEE Server Administration - Module 4 Load Balancer
Danairat Thanabodithammachari
ย 
Java Programming - 07 java networking
Danairat Thanabodithammachari
ย 
Java Programming - 08 java threading
Danairat Thanabodithammachari
ย 
Java Programming - 06 java file io
Danairat Thanabodithammachari
ย 
Java Programming - 05 access control in java
Danairat Thanabodithammachari
ย 

Recently uploaded (20)

PDF
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
ย 
PPTX
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
ย 
PPTX
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
ย 
PPTX
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
ย 
PDF
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
ย 
PDF
Automated Test Case Repair Using Language Models
Lionel Briand
ย 
PPTX
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
ย 
PPTX
Android Notifications-A Guide to User-Facing Alerts in Android .pptx
Nabin Dhakal
ย 
PDF
Rewards and Recognition (2).pdf
ethan Talor
ย 
PDF
AI Software Development Process, Strategies and Challenges
Net-Craft.com
ย 
PPTX
Iobit Driver Booster Pro 12 Crack Free Download
chaudhryakashoo065
ย 
PDF
Which Hiring Management Tools Offer the Best ROI?
HireME
ย 
PPTX
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
ย 
PPTX
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
ย 
PPTX
For my supp to finally picking supp that work
necas19388
ย 
PDF
OpenChain Webinar - AboutCode - Practical Compliance in One Stack โ€“ Licensing...
Shane Coughlan
ย 
PDF
Writing Maintainable Playwright Tests with Ease
Shubham Joshi
ย 
PDF
Telemedicine App Development_ Key Factors to Consider for Your Healthcare Ven...
Mobilityinfotech
ย 
PDF
TEASMA: A Practical Methodology for Test Adequacy Assessment of Deep Neural N...
Lionel Briand
ย 
PPTX
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
ย 
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
ย 
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
ย 
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
ย 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
ย 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
ย 
Automated Test Case Repair Using Language Models
Lionel Briand
ย 
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
ย 
Android Notifications-A Guide to User-Facing Alerts in Android .pptx
Nabin Dhakal
ย 
Rewards and Recognition (2).pdf
ethan Talor
ย 
AI Software Development Process, Strategies and Challenges
Net-Craft.com
ย 
Iobit Driver Booster Pro 12 Crack Free Download
chaudhryakashoo065
ย 
Which Hiring Management Tools Offer the Best ROI?
HireME
ย 
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
ย 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
ย 
For my supp to finally picking supp that work
necas19388
ย 
OpenChain Webinar - AboutCode - Practical Compliance in One Stack โ€“ Licensing...
Shane Coughlan
ย 
Writing Maintainable Playwright Tests with Ease
Shubham Joshi
ย 
Telemedicine App Development_ Key Factors to Consider for Your Healthcare Ven...
Mobilityinfotech
ย 
TEASMA: A Practical Methodology for Test Adequacy Assessment of Deep Neural N...
Lionel Briand
ย 
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
ย 

Perl Programming - 03 Programming File

  • 1. 03- Perl Programming File 134 Danairat T. Line ID: Danairat FB: Danairat Thanabodithammachari +668-1559-1446
  • 2. 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
  • 3. 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
  • 4. 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/perl use strict; use warnings; my $myFile = "fileread.txt"; # the file โ€œfiletest.txtโ€ must be exist my $myLine; if (open (MYFILEHANDLE, $myFile)) { while ($myLine = <MYFILEHANDLE>) { # read line chomp($myLine); # trim whitespace at end of line print "$myLine n"; } close (MYFILEHANDLE); } else { print "File could not be opened. n"; } exit(0); OpenFileEx01.pl Results:- <print the file content>
  • 5. 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 +>> โœ“
  • 6. Danairat T. Open File Options 139 โ€ข Using < for file reading. #!/usr/bin/perl use strict; use warnings; my $myFile = "fileread.txt"; # the file โ€œfiletest.txtโ€ must be exist my $myLine; if (open (MYFILEHANDLE, '<' , $myFile)) { # using โ€˜<โ€˜ and . for file read while ($myLine = <MYFILEHANDLE>) { # read line chomp($myLine); # trim whitespace at end of line print "$myLine n"; } close (MYFILEHANDLE); } else { print "File could not be opened. n"; } exit(0); OpenFileReadEx01.pl Results:- <print the file content>
  • 7. Danairat T. Open File Options 140 โ€ข Using > for file writing to new file. #!/usr/bin/perl use 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>
  • 8. 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/perl use 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>
  • 9. 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
  • 10. Danairat T. File Locking โ€“ Exclusive Locking 143 #!/usr/bin/perl use strict; use warnings; use Fcntl; my $file = 'testfile.txt'; # open the file open (FILE, ">>", "$file") || die "problem opening $filen"; # immediately lock the file flock (FILE, 2); # test keeping the lock on the file for ~20 seconds my $count = 0; while ($count++ < 30) { print "count = $countn"; print FILE "count = $countn"; sleep 1; } # close the file, which also removes the lock close (FILE); exit(0); FileExLockEx01.pl Please run this concurrence with FileExLockEx02.pl, see next page. Results:- <see from the output file>
  • 11. Danairat T. File Locking โ€“ Exclusive Locking 144 #!/usr/bin/perl use strict; use warnings; use Fcntl; my $file = 'testfile.txt'; # open the file open (FILE, ">>", "$file") || die "problem opening $filen"; # immediately lock the file flock (FILE, 2); # test keeping the lock on the file for ~20 seconds my $count = 0; while ($count++ < 30) { print "count : $countn"; print FILE "count : $countn"; sleep 1; } # close the file, which also removes the lock close (FILE); exit(0); FileExLockEx02.pl Please run this concurrency with FileExLockEx01.pl Results:- <see from the output file>
  • 12. Danairat T. File Locking โ€“ Shared Locking 145 #!/usr/bin/perl use strict; use warnings; use Fcntl; my $file = 'testfile.txt'; # open the file open (FILE, "<", "$file") || die "problem opening $filen"; # immediately lock the file flock (FILE, 1); # test keeping the lock on the file for ~20 seconds my $count = 0; while ($count++ < 30) { print "Shared Lockingn"; sleep 1; } # close the file, which also removes the lock close (FILE); exit(0); FileShLockEx01.pl Please run this concurrency with FileExLockEx02.pl Results:- <see from the output file>
  • 13. Danairat T. Filehandle Examples 146 โ€ข Read file and write to another file #!/usr/bin/perl use strict; use warnings; my $myFileRead = "fileread.txt"; my $myFileWrite = "filewrite.txt"; if (open (MYFILEREAD, '<' , $myFileRead)) { # using โ€˜<โ€˜ and . for file read if (open (MYFILEWRITE, '>' , $myFileWrite)) { while (my $myLine = <MYFILEREAD>) { # read line chomp($myLine); # trim whitespace at end of line print MYFILEWRITE "$myLinen"; } 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>
  • 14. Danairat T. Filehandle Examples 147 โ€ข Copy File using module File::Copy #!/usr/bin/perl use strict; use warnings; use File::Copy; my $myFileRead = "fileread.txt"; my $myFileWrite = "filewrite.txt"; if (copy ($myFileRead, $myFileWrite)) { print "success copy from $myFileRead to $myFileWritenโ€œ; } exit(0); CopyEx01.pl Results:- success copy from fileread.txt to filewrite.txt
  • 15. 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/perl use 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
  • 16. Danairat T. Filehandle Examples 149 โ€ข Create directory and move with rename the file #!/usr/bin/perl use 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 $myFileWriten"; } else { print "Unsuccess move from $myFileRead to ${myPath}${myFileWrite}n" } exit(0); FileMoveEx01.pl Results:- Success move from fileread.txt to ./mypath/filewrite.txt
  • 17. Danairat T. Filehandle Examples 150 โ€ข Read file to array at one time #!/usr/bin/perl use 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>
  • 18. Danairat T. Test File 151 โ€ข -e is the file exists. โ€ข -T is the file a text file โ€ข -r is the file readable #!/usr/bin/perl use 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
  • 19. 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);
  • 20. Danairat T. File stat() 153 โ€ข File statistic using stat(); #!/usr/bin/perl use 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
  • 21. Danairat T. File and Regular Expression 154 โ€ข Reading the configuration file param1=value1 param2=value2 param3=value3 config.conf
  • 22. Danairat T. File and Regular Expression 155 โ€ข Reading the configuration file #!/usr/bin/perl use strict; use warnings; my $myConfigFile = "config.conf"; my %configHash = (); exit (0) unless ( open (MYCONFIG, '<' , $myConfigFile) ); while (<MYCONFIG>) { chomp; # no newline s/#.*//; # no comments s/^s+//; # no leading white s/s+$//; # no trailing white next 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
  • 23. Danairat T. Line ID: Danairat FB: Danairat Thanabodithammachari +668-1559-1446 Thank you