Contents Perl Taking Input from user

PERL - <STDIN>

<STDIN> stands for standard input. It can be abbreviated by using simple <>. By declaring a scalar variable and setting it equal to <STDIN> we set the variable equal to whatever will be typed by our user at the command prompt. Observe:

whatismyage.pl:

#! usr/bin/perl
print "How old are you?";
$age = <>;
print "WOW! You are $age years old!";

How old are you?:

Screen Capture of Command Prompt

Don't worry about the display being a little off the mark, we will cover the formatting in the next lesson. For now let's practice retrieving some user input using PERL.

Let's take this example one step further and also request the favorite color of our user.

agencolor.pl:

#! usr/bin/perl
print "How old are you?";
$age = <>;
print "What is your favorite color?";
$color = <>;
print "You are $age, and your favorite color is $color.";

Age 'N' Color:

Screen Capture of Command Prompt

Once again, our formatting leave a little to be desired, but the variables are working as they should, and for now this is all we need to know.

PERL - Beginning Scripting

You now have the knowledge required to code some mathematical scripts like the following.

circle.pl:

#! usr/bin/perl
print "What is the radius of the circle?";
chomp ($r = <>);
$diameter = (2 * $r);
$area = (3.14 * ($r ** 2));
$cir = ($diameter * 3.14);
print "Radius: $r\n Diameter: $diameter\n Circumference: $cir\n Area: $area";

Circles!:

Screen Capture of Command Prompt

 

PERL - Chomp

Let's take another look at our agencolor.pl script. This script asked for two user inputs and returned an unformatted string and our variables as a result on the last line.

agencolor.pl:

#! usr/bin/perl
print "How old are you?";
$age = <>;
print "What is your favorite color?";
$color = <>;
print "You are $age, and your favorite color is $color.";

Here we have asked two questions, stored the user's input into two separate variables and printed out the results all in just a few lines of code. Be sure to take note of the formatting here. The user is required to strike the "enter" key resulting in a line break. We can remove the line break rather easily with the chomp() function. This function simply removes any erroneous line breaks and spacing from the end of our string.

agencolor2.pl:

#! usr/bin/perl
print "How old are you?";
chomp ($age = <>);
print "What is your favorite color?";
chomp ($color = <>);
print "You are $age, and your favorite color is $color.";

Age 'N' Color 2:

Screen Capture of Command Prompt

Chomp should be used whenever input is acquired from your users.

Want Some more information and Video ???

Home