So $a=<STDIN>; reads one line in $a, while @a=<STDIN> reads all lines into @a.
A line in Perl always includes a \n (newline) at the end, and we have to remove it before processing the line value. We use chop($var) to remove the \n.
A common pattern to read, remove the newline and process input is as follows: while (<STDIN>) { chop; statements using $_ and other variables } .
Please note that we are using while to create a loop controlled by the default $_= <STDIN> scratch variable, and also using the $_ by default in chop, as if we have written chop($_). See example 7
Pattern: print "text $var \n"; Simple format is also provided by printf.
Pattern: printf "format", v1, v2, vn , where the format is comprised by %xs, %yd and %z.yf, separated by commas and followed by \n. This means that you will have a variable with x string characters, with y numeric decimal integer number, and with z decimal digits followed by y digits after the decimal point for floating-point numbers.
Perl calls "filehandles" the logical names of the files opened.
Patterns: open (filehandle, "fname"); open (filehandle, ">fname"); and open (filehandle, ">>fname"); respectively, open for input, output and input/output -- append. The "fname" is the external, system, name of the file, while filehandle is the internal, logical, name of the file.
Example: open (DATA, "file.txt"); and use <DATA> with angled brackets to represent I/O like in <STDIN>.
Please note that it is recommended that filehandles be capitalized. Also, Pattern: close (filehandle); See example 8
Pattern: open (filehandle, "fname") | | die " Sorry I couldn't open the file\n"
See example 9 for a combination of file I/O with functions.
This page is maintained by Al Bento who can be reached at abento@ubalt.edu. This page was last updated on September 20, 2004. Although we will attempt to keep this information accurate, we can not guarantee the accuracy of the information provided.