|Perl Monk, Perl Meditation|
Basic Input and Outputby root (Scribe)
|on Nov 05, 1999 at 05:53 UTC||Need Help??|
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: <STDIN> or <FILE>.
<> or <STDIN> amount to input from the keyboard unless you have redefined <STDIN> 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.
Note in the while loop above Perl automatically put the input into the default variable: $_. Perl does this whenever a test for a loop consists of only reading input like <..>. If this is the case Perl just plops the line read into $_;
Some useful functions to use with <> are chomp and chop. Both remove things from the end of a string. In chop's case it removes the last character from a string. In chomp's case it removes the suffix of the string only if it matches the input record separator $/ which is by default the newline character(\n). Both can take a scalar or array of strings to act on as their argument. If no argument is used the default of $_ is assumed.
Output is straightforward with perl. Basically the print statement takes a string or list of strings and sends them to standard output. Here are some examples:
The printf function gives you a lot more control over your output. If you're familiar with C you'll know basically how this works. A quick example:
This results in $a getting printed as an integer in a 3 space field followed by a space, then $b printed as a float in a field of size seven with 2 decimal digits, then a space and then $c as 5 character field.
You should now learn about File Input and Output