In the Unix world (where Perl was born) everything is a file. To send a prompt to a user, you print to STDOUT. To read input from the user you read from STDIN. By default, STDOUT will go to the user's terminal/window and STDIN will come from their keyboard. If you write your code using these assumptions then people will be able to redirect stuff into your scripts or redirect the output. They will be able to do things you never imagined.
So, to read a line of input:
my $line = <STDIN>;
Or just:
my $line = <>;
Don't forget to chomp($line) to get rid of the trailing newline.
To prompt the user:
print "Enter a number: ";
You may need to set $| to have the prompt appear instead of being held up in a buffer.
Hope you get a good grade.
Update: I forgot to mention that if you really need to read from the keyboard (say one character at a time without waiting for enter) then look into Term::ReadKey
| [reply] [d/l] [select] |
Hi. I understand Standard Input; the real question I had was how do I take that and tell perl to *3-1 or a function like that? I want to tell it to do something with it for an output.
-@rocks
| [reply] |
Using eval is one solution:
$_ = <STDIN>;
print eval;
| [reply] [d/l] |
#!/usr/bin/perl
use warnings;
use strict;
my $input;
print("Your number: "), chomp( $input = <STDIN> )
until $input =~ /^\d+$/;
print 3 * $input - 1, $/;
The print, chomp sequence uses the comma operator to make the two part of a single expression for the modifier. The alternative is do { print... ; chomp ...;} until ...;.
After Compline, Zaxo | [reply] [d/l] |
(Looks like the server is not working properly at this moment, it is not taking posts, try again).I cooked a little bit:
while (<STDIN>) {
chomp;
if ($_ eq "quit") {
exit;
}
print eval "$_", "\n";
}
Sample input output would be: (user in put in red, output in blue):
$a=2
2
$a+3
5
($a+5)*2
14
quit
| [reply] [d/l] |
Others have correctly answered this question for normal, command line Perl scripts, referring to STDIN. However, for completeness, there is another case: that of GUI programming. How does one get access to the keyboard from a Tk application?
Over and above text fields, where the default bindings allow cursor based editing, you may find that you need to add bindings in order to trap certain keystrokes and key combinations.
In the case of a GUI application, STDOUT (and STDERR) go to the command window, if the application has been invoked with one. Just for the record, for CGI applications, STDIN is used to read POST data, STDOUT is used to send HTTP data (normally HTML, but could be graphical), and STDERR writes to the webserver's error log file. | [reply] |