Monday 4 September 2017

Getting user input using <> and running the script in Strawberry Perl

In a previous article I demonstrated how we could get user input in a perl script using the <STDIN> operator. In this article we'll use <> instead of <STDIN> and run the script using Strawberry Perl on Windows Platform and share couple of other things.

#!/usr/bin/perl -w

$|=1; #turn on autoflush

print "Enter your name: ";
chomp(my $name=<>); #remove new line from input

print 'You entered '.$name.' as your name'."\n"; #A difficult way to interpolate a scaler.
#Don't use this

print "Are you sure that $name is correct? \n"; #The easy way to interpolate a scalar.
#Use this.


Given below is a sample execution:

Enter your name: sahil
You entered sahil as your name
Are you sure that sahil is correct?


When running and without turning on autoflush the output seemed to be getting buffered i.e. When I ran the script I got a blank prompt and when I typed a string and pressed enter I saw all the print statements being printed in one go. This generally does not happen in UNIX and to prevent this behavior in UNIX or Windows we turn on autoflush by setting the value $| to 1.

The other thing I wanted to show you here is the use of the concatenation (.) operator while writing a print statement using single quotes. Variables don't get interpolated in single quotes but do get interpolated if left unquoted as shown. the new line (\n) escape sequence does not come into affect unless placed within double quotes. That is an exhausting way to write a print statement with variables in it.
I wanted to show it because it's possible but strongly advise against its usage.

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...