<STDIN> as a Scalar Value OR Getting User Input

At this point, if you're a typical code hacker, you're probably wondering how to get a value into a Perl program.  Here's the simplest way.  Each time you use <STDIN>1 in a place where a scalar value is expected, Perl reads the next complete text line from standard input (up to the first newline), and uses that string as the value of <STDIN>.  Standard input can mean many things, but unless you do something uncommon, it means the terminal of the user who invoked your program (probably you).  If there's nothing waiting to be read (typically the case, unless you type ahead a complete line), the Perl program will stop and wait for you to enter some characters followed by a newline (carriage return / linefeed).2

The string value of <STDIN> typically has a newline on the end of it.3  So, you could do something like this:

$line = <STDIN>;
if ($line eq "\n") {

	print "That was just a blank line!\n";

}
else {

	print "That line of input was:  $line";

}

But in practice, you don't often want to keep the newline, so you need the previously seen chomp function.

Next:  Output with print

OR

Main menu for this topic
























1 This is actually a line-input operator working on the filehandle STDIN (more on filehandles later).

Return to the page from whence you came
























2 To be honest, it's normally your system that waits for the input; Perl waits for your system.  Although the details depend upon your system and its configuration, you can generally correct your mistyping with a backspace key before you press return - your system handles that, not Perl itself.  If you need more control over input, get the Term::ReadLine module from CPAN.

Return to the page from whence you came
























3 The exception is if the standard input stream somehow runs out in the middle of a line.  But that's not a proper text file, of course.

Return to the page from whence you came