Basic Input and Output

In keeping with its UNIX heritage, Perl assumes, unless you specify otherwise, that input to your program comes from a file/channel called STDIN (standard input) and output from your program is sent to STDOUT (standard output).

On most computer systems, STDIN is the input you type in via the keyboard into a shell or terminal window and STDOUT is the text that the program displays in the same window.

You've already used STDOUT with this statement:

print "Hello World!\n";     # Prints to STDOUT by default

Data from STDIN can be read by using the expression <STDIN>

$inputline = <STDIN>;      # Reads in the contents of the next line from STDIN
                           # and assigns it to $inputline



Here is a simple script that uses both STDIN and STDOUT called greeting.pl

print "What is your first name?\n";
$first_name = <STDIN>;
print "What is your last name?\n";
$last_name = <STDIN>;
print "Hi " . $first_name ." " . $last_name . "!\n";

And this is what the execution looks like:

>perl greeting.pl
What is your first name?
Joe
What is your last name?
Programmer
Hi Joe
Programmer
!
>




You might have expected that the output would all appear on one line. The problem is that <STDIN> returns a new line, "\n", as is last character. To remove the last character from a string, you can use the built-in perl function chop(). Functions in Perl act on an arguement(s). Arguements follow the name of the function and are enclosed in parthentheses.
$first_name = "Joe\n";
chop($first_name);        #  removes the last character from $first_name
                          #  $first_name = "Joe";


Now let's redo the example above:

print "What is your first name?\n";
$first_name = <STDIN>;
chop($first_name);
print "What is your last name?\n";
$last_name = <STDIN>;
chop($last_name);
print "Hi " . $first_name ." " . $last_name . "!\n";


Here is is what the execution looks like now:

>perl greeting.pl
What is your first name?
Joe
What is your last name?
Programmer
Hi Joe Programmer!
>