Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Input/Output through the Keyboard

by grantm (Parson)
on Nov 13, 2002 at 02:47 UTC ( [id://212480]=note: print w/replies, xml ) Need Help??

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.


      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.


Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://212480]
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-04-21 16:50 GMT
Find Nodes?
    Voting Booth?

    No recent polls found