Sunday 3 September 2017

Getting user input in perl

The ability to gather, modify and update supplied user input is an important feature for any programming language and perl is no different in this regard.

In perl we use <STDIN> to prompt user for the input. The <> here is the line input operator working on the STDIN filehandle.

Whenever you use <STDIN> in a script, perl will expect a scalar value in it's place. Perl reads a line from STDIN and uses it as the value for <STDIN>.

The input we supply this way is often accompanied by a trailing new line (\n) character. For scripting purposes we need to remove this new line character because letting the new line persist within <STDIN> may lead to unexpected results in scripts.

Here is a sample script which prompts the user to input whether he wants to perform an addition or a subtraction operation. The user is then prompted to enter the numbers to be subtracted.
We could've asked the user to add numbers one after the other and store the numbers in separate scalar variables but I find using the list followed by split to be more convenient and more awesome.

Notice the use of chomp on both occasions while parsing input from the user. The script won't work without using the chomp() function at those instances. 

[root@pbox perl_programs]# cat elsif.pl
#!/usr/bin/perl -w
#
use strict;

print "Enter choice of operation add or sub: \n" ;
chomp (my $op =<STDIN>) ;

print "enter numbers separated by spaces \n" ;

chomp (my $input = <STDIN> ) ;
my @numbers =(split ' ', $input) ;

print "you entered the numbers: @numbers \n";

if ($op eq "add") { my $a = $numbers[0] + $numbers[1] ; print "$a \n"; }
elsif ($op eq "sub") { my $s = $numbers[0] - $numbers[1] ; print "$s \n"; }
else { print "You entered an invalid operation \n" ; }


Here's a sample run of the script:

./elsif.pl
Enter choice of operation add or sub:
add
enter numbers separated by spaces
10 200
you entered the numbers: 10 200
210

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...