5% assure discount from here only

Perl Input and Output

We are dealing with 2 types of Input and Output overhere.

(i) Basic Input and Output
(ii) File Input and Output


(i) Basic Input and Output:

Perl makes input and output extremely easy. When you know just a few simple things you'll find that you can read from the keyboard and display output to your monitor with ease. Once you get that down you'll find that reading and writing to files isn't much more difficult.

First we will show you how to read a line of text from the keyboard. It doesn't take much. All you need is the diamond, or spaceship operator which looks something like this: <>. You may also have the name of an optional stream inside of the diamond operator like: or .

<> or amount to input from the keyboard unless you have redefined or redirected a file to STDIN. The diamond operator by default reads to a newline or what ever is in $/ is set to. Ok enough talking, now for some quick examples.

$a=<>; #reads one line in from the keyboard including
#the newline character (\n) and puts it into $a

$b=; #does the same thing only puts it into $b;

while(<>){ #reads lines until end of file or a Control-D from t +he keyboard
print "$_"; #prints lines back out
}


(ii) File Input and Output

File input and output is not much of a stretch from normal I/O. Basically you have to use the open command to open a filestream and then read to and write from it. Then once you're done with it you use close to close the file. The syntax for opening a file is:

open(FILEHANDLE,"filename");

This opens a new filehandle with the name of FILEHANDLE, and associates it with filename which is the location of the file on your disk. This works for reading a file. If you want to write to it you need to put a > in front of the filename as seen below:

open(FILEHANDLE,">filename");

To append to a file you use >> in front of the filename as you can see here:

open(FILEHANDLE,">>filename");

Now for some quick examples:

open(FILE, "data.txt"); #opens data.txt in read-mode
while(){ #reads line by line from FILE which i +s the filehandle for data.txt chomp;
print "Saw $_ in data.txt\n"; #shows you what we have read
}
close FILE; #close the file.


There are different types of modes are available through which you can access the files, out of them some modes are:

The available modes are the following:

mode     operand     create     truncate
read         <

write        >                ✓           ✓
append     >>              ✓

Each of the above modes can also be prefixed with the + character to allow for simultaneous reading and writing.

mode             operand     create     truncate
read/write       +<

read/write       +>             ✓               ✓
read/append    +>>           ✓

So these modes are available to play with the files Input and Output.