STDIN in Perl is used to take input from the keyboard unless its work has been redefined by the user.
Syntax: <STDIN> or <>
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:
# 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 ;
|
Output:
Taking user Input without using <STDIN> in Scalar Context –
We can take user Input without using <STDIN>.
#!/usr/bin/perl print ( "Please enter your age : " );
$age = <>;
print ( "Your age is $age" );
|
output –
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:
# 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 ";
|
Output:
Taking user Input without <STDIN> in List Context –
We can also take user input in List Context using <> and to mark the end of taking input we will press CTRL+Z for Windows and CTRL+D for Linux.
#!/usr/bin/perl print ( "Enter the cities you have visited last year : " );
@cities = <>;
chomp @cities ;
print ( "You have visited the following cities @cities" );
|
Output –