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

More Related Content

What's hot (20)

Linux networking
Linux networkingLinux networking
Linux networking
Arie Bregman
 
2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge
Prof. Wim Van Criekinge
 
Linux administration training
Linux administration trainingLinux administration training
Linux administration training
iman darabi
 
Course 102: Lecture 6: Seeking Help
Course 102: Lecture 6: Seeking HelpCourse 102: Lecture 6: Seeking Help
Course 102: Lecture 6: Seeking Help
Ahmed El-Arabawy
 
Hive data migration (export/import)
Hive data migration (export/import)Hive data migration (export/import)
Hive data migration (export/import)
Bopyo Hong
 
Linux Fundamentals
Linux FundamentalsLinux Fundamentals
Linux Fundamentals
DianaWhitney4
 
Ansible for Beginners
Ansible for BeginnersAnsible for Beginners
Ansible for Beginners
Arie Bregman
 
Course 102: Lecture 3: Basic Concepts And Commands
Course 102: Lecture 3: Basic Concepts And Commands Course 102: Lecture 3: Basic Concepts And Commands
Course 102: Lecture 3: Basic Concepts And Commands
Ahmed El-Arabawy
 
(Practical) linux 104
(Practical) linux 104(Practical) linux 104
(Practical) linux 104
Arie Bregman
 
System Programming and Administration
System Programming and AdministrationSystem Programming and Administration
System Programming and Administration
Krasimir Berov (Красимир Беров)
 
Sahul
SahulSahul
Sahul
sahul azzez m.i
 
(Practical) linux 101
(Practical) linux 101(Practical) linux 101
(Practical) linux 101
Arie Bregman
 
Centralized + Unified Logging
Centralized + Unified LoggingCentralized + Unified Logging
Centralized + Unified Logging
Gabor Kozma
 
Tajo Seoul Meetup-201501
Tajo Seoul Meetup-201501Tajo Seoul Meetup-201501
Tajo Seoul Meetup-201501
Jinho Kim
 
Linux Shell Basics
Linux Shell BasicsLinux Shell Basics
Linux Shell Basics
Constantine Nosovsky
 
Linux Network commands
Linux Network commandsLinux Network commands
Linux Network commands
Hanan Nmr
 
Linux basic for CADD biologist
Linux basic for CADD biologistLinux basic for CADD biologist
Linux basic for CADD biologist
Ajay Murali
 
Unix - Filters/Editors
Unix - Filters/EditorsUnix - Filters/Editors
Unix - Filters/Editors
ananthimurugesan
 
Course 102: Lecture 12: Basic Text Handling
Course 102: Lecture 12: Basic Text Handling Course 102: Lecture 12: Basic Text Handling
Course 102: Lecture 12: Basic Text Handling
Ahmed El-Arabawy
 
linux-commandline-magic-Joomla-World-Conference-2014
linux-commandline-magic-Joomla-World-Conference-2014linux-commandline-magic-Joomla-World-Conference-2014
linux-commandline-magic-Joomla-World-Conference-2014
Peter Martin
 
2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge
Prof. Wim Van Criekinge
 
Linux administration training
Linux administration trainingLinux administration training
Linux administration training
iman darabi
 
Course 102: Lecture 6: Seeking Help
Course 102: Lecture 6: Seeking HelpCourse 102: Lecture 6: Seeking Help
Course 102: Lecture 6: Seeking Help
Ahmed El-Arabawy
 
Hive data migration (export/import)
Hive data migration (export/import)Hive data migration (export/import)
Hive data migration (export/import)
Bopyo Hong
 
Ansible for Beginners
Ansible for BeginnersAnsible for Beginners
Ansible for Beginners
Arie Bregman
 
Course 102: Lecture 3: Basic Concepts And Commands
Course 102: Lecture 3: Basic Concepts And Commands Course 102: Lecture 3: Basic Concepts And Commands
Course 102: Lecture 3: Basic Concepts And Commands
Ahmed El-Arabawy
 
(Practical) linux 104
(Practical) linux 104(Practical) linux 104
(Practical) linux 104
Arie Bregman
 
(Practical) linux 101
(Practical) linux 101(Practical) linux 101
(Practical) linux 101
Arie Bregman
 
Centralized + Unified Logging
Centralized + Unified LoggingCentralized + Unified Logging
Centralized + Unified Logging
Gabor Kozma
 
Tajo Seoul Meetup-201501
Tajo Seoul Meetup-201501Tajo Seoul Meetup-201501
Tajo Seoul Meetup-201501
Jinho Kim
 
Linux Network commands
Linux Network commandsLinux Network commands
Linux Network commands
Hanan Nmr
 
Linux basic for CADD biologist
Linux basic for CADD biologistLinux basic for CADD biologist
Linux basic for CADD biologist
Ajay Murali
 
Course 102: Lecture 12: Basic Text Handling
Course 102: Lecture 12: Basic Text Handling Course 102: Lecture 12: Basic Text Handling
Course 102: Lecture 12: Basic Text Handling
Ahmed El-Arabawy
 
linux-commandline-magic-Joomla-World-Conference-2014
linux-commandline-magic-Joomla-World-Conference-2014linux-commandline-magic-Joomla-World-Conference-2014
linux-commandline-magic-Joomla-World-Conference-2014
Peter Martin
 

Viewers also liked (15)

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

Similar to Perl Programming - 03 Programming File (20)

Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
TAlha MAlik
 
Ch3(working with file)
Ch3(working with file)Ch3(working with file)
Ch3(working with file)
Chhom Karath
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
File io
File ioFile io
File io
Pri Dhaka
 
Filing system in PHP
Filing system in PHPFiling system in PHP
Filing system in PHP
Mudasir Syed
 
pointer, structure ,union and intro to file handling
 pointer, structure ,union and intro to file handling pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
File management
File managementFile management
File management
Mohammed Sikander
 
Diploma ii cfpc- u-5.2 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.2 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.2 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.2 pointer, structure ,union and intro to file handling
Rai University
 
File system
File systemFile system
File system
Gayane Aslanyan
 
Aray in Programming
Aray in ProgrammingAray in Programming
Aray in Programming
javeriagulzar
 
File handling in c
File  handling in cFile  handling in c
File handling in c
thirumalaikumar3
 
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdfProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
lailoesakhan
 
BITS: Introduction to Linux - Text manipulation tools for bioinformatics
BITS: Introduction to Linux - Text manipulation tools for bioinformaticsBITS: Introduction to Linux - Text manipulation tools for bioinformatics
BITS: Introduction to Linux - Text manipulation tools for bioinformatics
BITS
 
Path::Tiny
Path::TinyPath::Tiny
Path::Tiny
waniji
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
Krasimir Berov (Красимир Беров)
 
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
Bhavsingh Maloth
 
(C Program to Simulate a UNIX-based filesystem) My goal is to implem.docx
(C Program to Simulate a UNIX-based filesystem) My goal is to implem.docx(C Program to Simulate a UNIX-based filesystem) My goal is to implem.docx
(C Program to Simulate a UNIX-based filesystem) My goal is to implem.docx
ajoy21
 
Log into your netlab workstation then ssh to server.cnt1015.local wi.docx
Log into your netlab workstation then ssh to server.cnt1015.local wi.docxLog into your netlab workstation then ssh to server.cnt1015.local wi.docx
Log into your netlab workstation then ssh to server.cnt1015.local wi.docx
desteinbrook
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
yuvrajkeshri
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
TAlha MAlik
 
Ch3(working with file)
Ch3(working with file)Ch3(working with file)
Ch3(working with file)
Chhom Karath
 
Filing system in PHP
Filing system in PHPFiling system in PHP
Filing system in PHP
Mudasir Syed
 
pointer, structure ,union and intro to file handling
 pointer, structure ,union and intro to file handling pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
Diploma ii cfpc- u-5.2 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.2 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.2 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.2 pointer, structure ,union and intro to file handling
Rai University
 
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdfProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
lailoesakhan
 
BITS: Introduction to Linux - Text manipulation tools for bioinformatics
BITS: Introduction to Linux - Text manipulation tools for bioinformaticsBITS: Introduction to Linux - Text manipulation tools for bioinformatics
BITS: Introduction to Linux - Text manipulation tools for bioinformatics
BITS
 
Path::Tiny
Path::TinyPath::Tiny
Path::Tiny
waniji
 
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
Bhavsingh Maloth
 
(C Program to Simulate a UNIX-based filesystem) My goal is to implem.docx
(C Program to Simulate a UNIX-based filesystem) My goal is to implem.docx(C Program to Simulate a UNIX-based filesystem) My goal is to implem.docx
(C Program to Simulate a UNIX-based filesystem) My goal is to implem.docx
ajoy21
 
Log into your netlab workstation then ssh to server.cnt1015.local wi.docx
Log into your netlab workstation then ssh to server.cnt1015.local wi.docxLog into your netlab workstation then ssh to server.cnt1015.local wi.docx
Log into your netlab workstation then ssh to server.cnt1015.local wi.docx
desteinbrook
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
yuvrajkeshri
 
Ad

More from Danairat Thanabodithammachari (16)

Thailand State Enterprise - Business Architecture and SE-AM
Thailand State Enterprise - Business Architecture and SE-AMThailand State Enterprise - Business Architecture and SE-AM
Thailand State Enterprise - Business Architecture and SE-AM
Danairat Thanabodithammachari
 
Agile Management
Agile ManagementAgile Management
Agile Management
Danairat Thanabodithammachari
 
Agile Organization and Enterprise Architecture v1129 Danairat
Agile Organization and Enterprise Architecture v1129 DanairatAgile Organization and Enterprise Architecture v1129 Danairat
Agile Organization and Enterprise Architecture v1129 Danairat
Danairat Thanabodithammachari
 
Blockchain for Management
Blockchain for ManagementBlockchain for Management
Blockchain for Management
Danairat Thanabodithammachari
 
Enterprise Architecture and Agile Organization Management v1076 Danairat
Enterprise Architecture and Agile Organization Management v1076 DanairatEnterprise Architecture and Agile Organization Management v1076 Danairat
Enterprise Architecture and Agile Organization Management v1076 Danairat
Danairat Thanabodithammachari
 
Agile Enterprise Architecture - Danairat
Agile Enterprise Architecture - DanairatAgile Enterprise Architecture - Danairat
Agile Enterprise Architecture - Danairat
Danairat Thanabodithammachari
 
Big data hadooop analytic and data warehouse comparison guide
Big data hadooop analytic and data warehouse comparison guideBig data hadooop analytic and data warehouse comparison guide
Big data hadooop analytic and data warehouse comparison guide
Danairat Thanabodithammachari
 
JEE Programming - 04 Java Servlets
JEE Programming - 04 Java ServletsJEE Programming - 04 Java Servlets
JEE Programming - 04 Java Servlets
Danairat Thanabodithammachari
 
JEE Programming - 07 EJB Programming
JEE Programming - 07 EJB ProgrammingJEE Programming - 07 EJB Programming
JEE Programming - 07 EJB Programming
Danairat Thanabodithammachari
 
Glassfish JEE Server Administration - JEE Introduction
Glassfish JEE Server Administration - JEE IntroductionGlassfish JEE Server Administration - JEE Introduction
Glassfish JEE Server Administration - JEE Introduction
Danairat Thanabodithammachari
 
Glassfish JEE Server Administration - Clustering
Glassfish JEE Server Administration - ClusteringGlassfish JEE Server Administration - Clustering
Glassfish JEE Server Administration - Clustering
Danairat Thanabodithammachari
 
Glassfish JEE Server Administration - Module 4 Load Balancer
Glassfish JEE Server Administration - Module 4 Load BalancerGlassfish JEE Server Administration - Module 4 Load Balancer
Glassfish JEE Server Administration - Module 4 Load Balancer
Danairat Thanabodithammachari
 
Java Programming - 07 java networking
Java Programming - 07 java networkingJava Programming - 07 java networking
Java Programming - 07 java networking
Danairat Thanabodithammachari
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
Danairat Thanabodithammachari
 
Java Programming - 06 java file io
Java Programming - 06 java file ioJava Programming - 06 java file io
Java Programming - 06 java file io
Danairat Thanabodithammachari
 
Java Programming - 05 access control in java
Java Programming - 05 access control in javaJava Programming - 05 access control in java
Java Programming - 05 access control in java
Danairat Thanabodithammachari
 
Thailand State Enterprise - Business Architecture and SE-AM
Thailand State Enterprise - Business Architecture and SE-AMThailand State Enterprise - Business Architecture and SE-AM
Thailand State Enterprise - Business Architecture and SE-AM
Danairat Thanabodithammachari
 
Agile Organization and Enterprise Architecture v1129 Danairat
Agile Organization and Enterprise Architecture v1129 DanairatAgile Organization and Enterprise Architecture v1129 Danairat
Agile Organization and Enterprise Architecture v1129 Danairat
Danairat Thanabodithammachari
 
Enterprise Architecture and Agile Organization Management v1076 Danairat
Enterprise Architecture and Agile Organization Management v1076 DanairatEnterprise Architecture and Agile Organization Management v1076 Danairat
Enterprise Architecture and Agile Organization Management v1076 Danairat
Danairat Thanabodithammachari
 
Big data hadooop analytic and data warehouse comparison guide
Big data hadooop analytic and data warehouse comparison guideBig data hadooop analytic and data warehouse comparison guide
Big data hadooop analytic and data warehouse comparison guide
Danairat Thanabodithammachari
 
Glassfish JEE Server Administration - JEE Introduction
Glassfish JEE Server Administration - JEE IntroductionGlassfish JEE Server Administration - JEE Introduction
Glassfish JEE Server Administration - JEE Introduction
Danairat Thanabodithammachari
 
Glassfish JEE Server Administration - Module 4 Load Balancer
Glassfish JEE Server Administration - Module 4 Load BalancerGlassfish JEE Server Administration - Module 4 Load Balancer
Glassfish JEE Server Administration - Module 4 Load Balancer
Danairat Thanabodithammachari
 

Recently uploaded (20)

Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint PresentationFrom Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
Shay Ginsbourg
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
Adobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 linkAdobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 link
mahmadzubair09
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdfProtect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
株式会社クライム
 
wAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptxwAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptx
SimonedeGijt
 
How to avoid IT Asset Management mistakes during implementation_PDF.pdf
How to avoid IT Asset Management mistakes during implementation_PDF.pdfHow to avoid IT Asset Management mistakes during implementation_PDF.pdf
How to avoid IT Asset Management mistakes during implementation_PDF.pdf
victordsane
 
Artificial hand using embedded system.pptx
Artificial hand using embedded system.pptxArtificial hand using embedded system.pptx
Artificial hand using embedded system.pptx
bhoomigowda12345
 
Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??
Web Designer
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025
Web Designer
 
GDS SYSTEM | GLOBAL DISTRIBUTION SYSTEM
GDS SYSTEM | GLOBAL  DISTRIBUTION SYSTEMGDS SYSTEM | GLOBAL  DISTRIBUTION SYSTEM
GDS SYSTEM | GLOBAL DISTRIBUTION SYSTEM
philipnathen82
 
Robotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptxRobotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptx
julia smits
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
How I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetryHow I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetry
Cees Bos
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
Sequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptxSequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptx
aashrithakondapalli8
 
Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025
Phil Eaton
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint PresentationFrom Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
Shay Ginsbourg
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
Adobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 linkAdobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 link
mahmadzubair09
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdfProtect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
株式会社クライム
 
wAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptxwAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptx
SimonedeGijt
 
How to avoid IT Asset Management mistakes during implementation_PDF.pdf
How to avoid IT Asset Management mistakes during implementation_PDF.pdfHow to avoid IT Asset Management mistakes during implementation_PDF.pdf
How to avoid IT Asset Management mistakes during implementation_PDF.pdf
victordsane
 
Artificial hand using embedded system.pptx
Artificial hand using embedded system.pptxArtificial hand using embedded system.pptx
Artificial hand using embedded system.pptx
bhoomigowda12345
 
Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??
Web Designer
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025
Web Designer
 
GDS SYSTEM | GLOBAL DISTRIBUTION SYSTEM
GDS SYSTEM | GLOBAL  DISTRIBUTION SYSTEMGDS SYSTEM | GLOBAL  DISTRIBUTION SYSTEM
GDS SYSTEM | GLOBAL DISTRIBUTION SYSTEM
philipnathen82
 
Robotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptxRobotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptx
julia smits
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
How I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetryHow I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetry
Cees Bos
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
Sequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptxSequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptx
aashrithakondapalli8
 
Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025
Phil Eaton
 

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
  翻译: