Reading user input.pl

From JaxHax
Jump to: navigation, search

reading_user_input.pl Overview

reading_user_input.pl is our third example which is a simple program that shows how to get user input during runtime via the use of STDIN and load it into a variable.


reading_user_input.pl Code

Save the code below in a file called reading_user_input.pl:

###############################################
#
# Example: reading_user_input.pl
#
# An example to show how to prompt a user for
# input and feed it into a variable.
#
###############################################
 
###
#### First use print to throw a prompt to the user.
#### notice there is no newline. Pay attention to that
#### when you run the program.
###
print "Please Enter your name: ";
 
###
#### Next, we read from <STDIN>. This will read input
#### till a newline is hit.
###
$name = <STDIN>;
 
###
#### Print hello to the person. Interesting part is the
#### newline is a part of this string. notice the print
#### here should run together on one line.
###
print "Hello $name. Nice to meet you.";
 
print "\n\n\nWhats your favorite color: ";
 
###
#### Now we will use the chomp() function. This function
#### will remove the trailing newline at the end.
###
$color = <STDIN>;
chomp($color);
 
###
#### Now notice how this works here with the New line.
#### Will this print on two lines, or just one?
###
print "\nyour favorite color is $color. Delightful...\n\n";

Running reading_user_input.pl from a Shell

[user@localhost]$ perl reading_user_input.pl
Please Enter your name: Travis
Hello Travis
. Nice to meet you.
 
 
Whats your favorite color: Black
 
your favorite color is Black. Delightful...
 
[user@localhost]$


Code Breakdown

In this program, we first throw a prompt using the "print" command. Notice on that print command we don't give a newline. This is because we want it to accept the user input on the same line. After that line we set a variable called $name equal to the file descriptor <STDIN>. STDIN is in "<>", which means it is a file descriptor. Using the STDIN file descriptor will read in what the user types in the keyboard until they hit enter which creates a newline. After that we will use the users input to greet them. If you will notice in the shell output though, when we greet the user the $name variable also contained the user's newline they typed as well.

Next we prompt the user asking for their favorite color. This time we will read the user input into a variable into $color. After we read in STDIN we place the variable into the chomp() function. The chomp() function will strip the newline off the end that the user will use to submit the data. Now we will print their favorite color out, but notice this time in the output it will run the output in one line.