http://qs321.pair.com?node_id=212480


in reply to Input/Output through the Keyboard

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

Replies are listed 'Best First'.
Re: Re: Input/Output through the Keyboard
by @rocks (Scribe) on Nov 13, 2002 at 04:25 UTC
    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

      Using eval is one solution:
      $_ = <STDIN>; print eval;
        Solution is further simplified after matter, the final solution is in above post.
        I cooked a little bit:
        while (<STDIN>) { chomp; if ($_ eq "quit") { exit; } print eval "$_", "\n"; }
        Hmm... This is interesting. I was thinking more on the lines of something that had to do with foreach except only dealing with the one variable you enter because of course your only enter one line. Something like:?

        #!/usr/bin/perl<P> $input=<>; foreach $input++1;
        but of course that doesn't work! I need to use foreach on arrays not scalars and I think I messed up the foreach thing too. A programmer told me that  evalis a module? I don't want to use modules.

        -@rocks