6.
Standard and File I/O
6.1 Files
File manipulations include reading, writing, and appending
external data files such as saved Email file, password file, log file, web
server error report file, and database file.
A password file can be used for access control to protect sensitive
information from prying eyes. We can set up several usernames and passwords to
direct users to specific areas of a web site based on their authentication.
Perl scripts can
be used to access data and document files on disk. It allows a user to
read/write text files from the command line and through a web browser
interface.
Perl scripts allow articles service automation. That is can be designed
to serve articles to a web browser as well as serving news articles based on
the time of day.
Perl scripts help
automating user comment gathering from users. The web server accepts data from
HTML forms through the CGI environmental variables. It
can be used to check required fields, display error messages, send results back
to the user, and write the results to a log file to keep track of your data. It
can also keeps statistics of the number of accesses, operating systems, browser
types and number of unique IP addresses that have accessed your site or
individual pages.
6.2 Standard Inputs and Outputs
In Perl, three
predefined I/O streams associated with terminals:
A file handle is a name
for an I/O connection between a running program called process and the outside
peripherals. Therefore, file handles for these three standard I/O are called
STDIN, STDOUT, and STDERR
STDIN file Handle for Reading Keyboard Input
chop () function
chomp() function
read() Function
Example 6-1: User input example.
#stdinex.pl
#
#OUTPUT:
# E:\Perl\Exs>perl stdinex.pl
# Enter your phone number = 4816339
# Enter Your First Name =Paul
# Enter Your Last Name =Lin
# You entered:
#
# Paul
# Lin
# 4816339
print "Enter
your phone number = ";
$phonenum =
<STDIN>;
print "Enter
Your First Name =";
$firstname =
<STDIN>;
print "Enter
Your Last Name =";
$lastname =
<STDIN>;
print "You
entered: \n\n";
print $firstname;
print $lastname;
print $phonenum;
Example 6-2: Chopping the new line character for displaying
inputs on a single line.
#stdinexchop.pl
#
#OUTPUT:
#
# E:\Perl\Exs>perl stdinexchop.pl
# Enter your phone number = 4816339
# Enter Your First Name =Paul
# Enter Your Last Name =Lin
# You entered:
#
# Paul
Lin 4816339
print "Enter your
phone number = ";
$phonenum =
<STDIN>;
chop($phonenum);
print "Enter
Your First Name = ";
chop($firstname =
<STDIN>);
print "Enter
Your Last Name = ";
chomp($lastname =
<STDIN>);
print "You
entered: \n\n";
print
"$firstname \t$lastname\t $phonenum";
6.3 Formatted Output
The printf() function uses format specifiers in
the format string for printing formats references. It defines the data to be
printed with appropriate display format on the standard output device (stdout)
or monitor screen. Some basic
characteristics of this function are
·
Writes character string and values of variables, formatted, to
“stdout”
·
printf (format_control);
·
Format control string supports the following display format:
Format Specifiers
·
%c -- character
·
%d -- signed integer,
in decimal
·
%o -- unsigned integer,
in octal
·
%u -- unsigned integer,
in decimal
·
%x -- unsigned integer,
in hexadecimal (a-f or A-F)
·
%f -- floating-point number, in fixed decimal
notation(default 6 digits)
·
%e -- floating-point number, in scientific
notation
·
%g -- floating-point number, in %e or %f form
·
%s --- string
·
%% --- for printing a
literal % symbol
It is possible to use
flags between the % sign and conversion character to modify the printing
format.
Flags Meaning
- Left justified printing
+ Print either + or - sign
0 Zero causes 0’s to be used for
padding
Width
(precision) Meaning
%10d, %10s At least 10-char
%.7s
At most 7-char
%14.8s 14-char in total, use only 8-char
%-7d Left
justify, min. field width 7
%8.2f Field width 8, precision 2
%05d Padding
with zeros
%-10.5e Left justified e format
An example
printf "%20S %4d %8.2f",
$name, $pidnum, %amount;
6.4 File Processing Functions
Perl supports a rich set
of file I/O functions for reading, writing, appending data to/from disk
storage. A file handle is needed for opening a new file, an existing file, etc.
A number of functions for file manipulation is listed below:
print
#
Output to standard output (stdout) device
open(FILEANDLE,
"file.html");
#
open a file for read, write, or append
open(FILEHANDLE,
">file.html");
#
use > to overwrite if file.html exists
open(FILEHANDLE,
">>file.html");
#
use >> to append if file.html content exists
open(FILEHANDLE,
"| \perl5/sbin\sendmail");
#
open a process
close(FILEHANDLE);
#
close a file or process
opendir(DIR,
"directory");
#
specify a file folder of directory
readdir(DIR);
#
allow the access of every file in the file folder that
#
specified by DIR file handle
closedir(DIR);
# close a directory file handle
Example 6-4: Reading an
external Email text file.
#!/usr/bin/perl
# reademail.pl
# Description:
# This program open an email file and print it.
# - EMAIL is a file handler as the open() function call.
# - prop.txt is a saved email file.
# - print function will display text on the STDOUT
# standard output
screen (monitor)
# - close(EMAIL) to return file handler to OS
#
open (EMAIL, "prop.txt");
while(<EMAIL>)
{
print;
}
close (EMAIL);
OUTPUT: Partial output
from monitor screen
...
The four parts are:
1) Setting up the
Microsoft Advanced Server platform
running IIS to
enable JAVA Servlets to be run.
2) Creating an HTML page
that will call the JAVA servlet
3) Creating a JAVA
servlet
4) Establishing database
connectivity with the servlet to Microsoft
Access database
...
Example 6-5: Reading a
saved Email text file through a browser. This Perl script is saved in the
cgi-bin directory. Remote access through a web browser is required to access
"reademail_html.pl" program.
#!/usr/bin/perl
# reademail_html.pl
# Description:
# This program open an email file and print it.
# - EMAIL is a file handler as the open() function call.
# - prop.txt is a saved email file.
# - print function will display text on the STDOUT
# standard output screen
(monitor)
# - close(EMAIL) to return file handler to OS
#
print "Content-type: text/html\n\n";
print "<HTML>\n";
print "<HEAD>\n";
print "<TITLE> Read Email </TITLE>\n";
print "</HEAD>\n";
print "<BODY BGCOLOR
=\"#FFFFFF\">\n\n";
open (EMAIL,
"prop.txt");
while(<EMAIL>)
{
print;
}
close (EMAIL);
print "</BODY>\n";
print "</HTML>\n";
6.5 Advanced File Manipulation Examples
Example 6-6: Locking and Unclocking Files
flock(FILEHANDLE,
operation);
Where operation can
be one of the following:
Name Operation Description
lock_sh 1 Create
a shared lock
lock_ex 2 Create
an exclusive lock
lock_nb 4 Create
a non-blocking lock
lock_un 8 Unlock
an existing lock
$lock_sh = 1; #Create a shared lock
$lock_ex = 2; #Create an exclusive lock so other can't
write to it
$lock_nb = 4; #Create a non-blocking lock
$lock_un = 8; #Unlock an existing lock
open(FILE1,
">>file.txt");
flock(FILE1,
"$lock_ex"); # lock the
file
print "FILE1,
"write some other data to the file that you locked";
flock(FILE1,
"$lock_un"); # unlock the
file
Example 6-7: print out every file and directory in the
current directory (.)
opendir(DIR,
"."); # open current
directory
foreach $name
(readdir(DIR))
{
print "$name\n\n";
}
closedir(DIR);