Perl | STDIN in Scalar and List Context

STDIN in Perl is used to take input from the keyboard unless its work has been redefined by the user.

Syntax: <STDIN>

STDIN in Scalar Context

 
In order to take input from the keyboard or operator is used in Perl. This operator reads a line entered through the keyboard along with the newline character corresponding to the ENTER we press after input.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Asking user for Input
print "What is your age?\n";
  
# Getting an age from the user
$age = <STDIN>;
  
# Removes new line from the input
chomp $age;
  
# Printing the value entered by user
print "Your age is ", $age;

chevron_right


Output:
 

So $age contains the input given by the user as well as the new line character. In order to remove the new line, chomp function is used which removes “\n” from the end of the string.
 

STDIN in List Context

 
When STDIN is used with list context, it takes multiple values as an input from the keyboard. Press ENTER to indicate individual elements in the list. In order to indicate the ending of inputs, press Ctrl-D in Linux systems whereas Ctrl-Z in Windows system.
The example below shows the use of STDIN in list context.
Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Get a city name from the user 
print "Enter the cities you have visited last year... ";
print "<Ctrl>-D to Terminate \n";
@city = <STDIN>;
  
# Removes new line appended at 
# the end of every input
chomp @city;
  
# Print the city names
print "\nCities visited by you are: \n@city ";

chevron_right


Output:
 

Here is how the above program works:
Step 1: Get List input from the user separated by ENTER.
Step 2: When Ctrl-D is pressed it indicates the ending of inputs, so, Perl assigns everything to the @city array.
Step 3: Use chomp function to remove new line from all the inputs.
Step 4: Printing the city names given as in input.



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.