Perl I/O Statements


I/O Statements

  1. <STDIN> In a scalar context it gives the next line of the standard input device, or undef if there are no more lines. In an array context gives all lines as a list.

    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

  2. Print/Printf. Print the output to either STDOUT -- the standard output device, or to a file handle (we will see filehandles below in the Open statement.

    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.

  3. Open/Close. Open selects a file to be used as input, output or input/output, instead of STDIN and STDOUT.

    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

  4. Die. Allow testing if the open was successful, meaning if you could open the file. It is used with open.

    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.