Perl allows the programmer to accept input from the user to perform operations on. This makes it easier for the user to give input of its own and not only the one provided as Hardcoded input by the programmer. This Input can then be processed and printed with the use of print() function. Input to a Perl program can be given by keyboard with the use of <STDIN>. Here, STDIN stands for Standard Input. Though there is no need to put STDIN in between the ‘diamond’ or ‘spaceship’ operator i.e, <>. It is standard practice to do so. <> operator can be used to write to files as well. <STDIN> can be also be used in Scalar and List context.
Syntax: $x = <STDIN>; or $x = <>;
Example:
Perl
#!/usr/bin/perl -w
use strict;
use warnings;
print "Enter some text:";
my $string = <STDIN>;
print "You entered $string as a String";
|
Input:
GeeksForGeeks
Output:
Enter some text: GeeksForGeeks
You Entered GeeksForGeeks
as a String
In the above code, after giving Input, there is a need to press ENTER. This ENTER is used to tell the compiler to execute the next line of the code. But, <STDIN> takes this ENTER key pressed as a part of the Input given and hence when we print the line. A new line will automatically be printed after the Input string. To avoid this, a function chomp() is used. This function will remove the newline character added to the end of the Input provided by the user. Example:
Perl
#!/usr/bin/perl -w
use strict;
use warnings;
print "Enter some text:";
my $string = <STDIN>;
chomp $string ;
print "You entered $string as a String";
|
Input:
GeeksForGeeks
Output:
Enter some text: GeeksForGeeks
You Entered GeeksForGeeks as a String
Taking Input using just <> –
Without using STDIN or stdin we can take user input just by using <>.
Perl
#!/usr/bin/perl
print ( "Please enter your age : " );
$age = <>;
print ( "Your age is $age" );
|
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
18 Feb, 2023
Like Article
Save Article