Perl - Basic Input/output

December 2016



Perl - standard input and output


Perl allows you to write to standard output, called STDOUT and read standard input (STDIN). These two descriptors are provided by the operating system, allows the reading of keyboard input and the display of data on thescreen. In fact, Perl is based on UNIX systems, on which the input-output are considered files.
For example, on a Web server using CGI scripts, the standard input is the HTTP request, and the standard output the HTTP response.

Reading the standard input


The data coming from standard input (defined by the operating system) are available in the Perl environment via the <STDIN> descriptor. In this way, it is possible to recover (line by line) the contents of this descriptor using a specific variable and assignment operator:
$var = <STDIN>

It is also possible to use an array variable in which we will concatenate each line:
@var = <STDIN>

In this way, through a loop, you can recover all the lines of the standard input. When there are no more lines available in the standard input, it returns the "undef" value, which means that no value is set, and the loop ends. An example of a loop:
while ($var = <STDIN>) {
// instructions
}

Writing to stdout


To write to standard output just use the print() function:
$var = 'Hello';
print ($var.' world');

These instructions have the effect of sending the string "Hello World" to standard output. Here the concatenation operator (".") Was used to join the two strings. It is also possible to use double quotes to interpolate the $var variable, that is to say, replaced its contents:
$var = 'hello';
print ("$var world");

This function can also be used in a radically different syntax, making more apparent the role of the standard output (STDOUT):
$var = 'Hello';
print STDOUT $var;

In reality, STDOUT being the "standard" output (by default), the easiest way to write this code is:
$var = 'bonjour';
print $var;

It is also possible to use the printf() (from the C language) to send information to the standard output.

The standard error output


Perl provides a third standard descriptor to automatically send errors to a specific output, as defined by the system administrator. This descriptor is called STDERR.
Orignal document published on CommentCaMarche.net.

Related :

This document entitled « Perl - Basic Input/output » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.