Close
Close

Taking Input in Perl


You will learn to take input from users in this chapter. We do this by using <> operator in Perl. This operator reads a line entered through the keyboard along with the newline character. Let's see this example and then we will discuss more about this.

print "What is your name?\n";
$name = <>;
print "Your name is ",$name;
Output
What is your name
Sam
Your name is Sam

<> operator is used to take input and it did the same. It took an input from the user.
$name = <>; - This line means that the variable 'name' is equal to the input taken as <> returns the taken input.
One more thing you should notice here is that <> also returned a newline character corresponding to the ENTER we pressed after giving input.

To get rid of this newline character, we use chomp function. It just removes the newline character from the end.

print "What is your name?\n";
$name = <>;
chomp($name);
print "Your name is ",$name,"\n";
Output
What is your name
Sam
Your name is Sam

As mentioned earlier, Perl strings and numbers are seamlessly converted into each other depending on the context in which they are used. So, there is no need to take separate inputs for numbers. Let's see an example:

print "Enter a number\n";
$number = <>;
chomp($number);
print $number*2,"\n";
Output
Enter a number
10
20

So you just saw that the input was converted to an integer when it was needed. However, if you want to convert it into a number, you can do it as follows:

print "Enter a number\n";
$number = <>;
#convert to integer
$number = $number*1;
Output
Enter a number
10

Taking command line arguments


We run a Perl script by writing perl filename.pl (filename is the name of file). Taking command line arguments means to pass some argument (or give input) while calling this command to run a Perl script. For example, to give 5 as input, writing this command - perl filename.pl 5 or to pass both 5 and 10, writing this - perl filename.pl 5 10.

We do this by using @ARGV array. You will learn about arrays in a separate chapter, for now keep in mind that the first passed argument is stored in a variable $ARGV[0], second in $ARGV[1] and so on. Let's see an example of passing two numbers and printing their sum. We will get the first passed number by $ARGV[0] and the second by $ARGV[1].

#Command given perl filename.pl 5 10
#filename is the name of file
print "$ARGV[0]+$ARGV[1] is ",$ARGV[0]+$ARGV[1],"\n";
Output
5+10 is 15
Ask Yours
Post Yours
Doubt? Ask question