These snippets demonstrate console input and output in Perl. The first snippet simply asks for input and outputs it back to you and the second snippet interprets commands and displays the results.
Receive user input and print it back
#!/usr/bin/perl print "Your input: "; # Receive user input from standard input my $consoleInput = <STDIN>; # Output the received input print "You entered: ".$consoleInput."\n";
Output:
Your input: hello You entered: hello
Interpret commands and print the results
#!/usr/bin/perl use Switch; use POSIX qw(strftime); # Show the available commands printHelp(); # Loop continuesly and ask for command input while(1){ print "> "; chomp($commandInput = <STDIN>); switch($commandInput){ case "help" { printHelp(); } case "date" { printDate(); } case "exit" { die "Goodbye!"; } # Print an error message when the user enters an invalid command else { printError(); } } } # Prints the help message sub printHelp(){ print "The available commands are: \n". "help - Prints this help message \n". "date - Prints the current date and time \n". "exit - Quits this script\n"; } # Displays the current date and time sub printDate(){ print strftime('%d-%m-%Y %H:%M:%S', localtime)."\n"; } # Prints an error message sub printError(){ print "Invalid command\n"; }
Output:
The available commands are: help - Prints this help message date - Prints the current date and time exit - Quits this script > date 20-05-2011 19:53:10 > help The available commands are: help - Prints this help message date - Prints the current date and time exit - Quits this script > exit Goodbye! at command.pl line 17, <STDIN> line 3.