Perl | Use of STDIN for Input

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl -w 
use strict;
use warnings;
  
print"Enter some text:";
my $string = <STDIN>;
  
print "You entered $string as a String";

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl -w 
use strict;
use warnings;
  
print"Enter some text:";
my $string = <STDIN>;
chomp $string;
  
print "You entered $string as a String";

chevron_right


Input:

GeeksForGeeks

Output:

Enter some text: GeeksForGeeks
You Entered GeeksForGeeks as a String


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.