LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   console input in perl! (https://www.linuxquestions.org/questions/programming-9/console-input-in-perl-64917/)

farhanali 06-11-2003 02:44 AM

console input in perl!
 
hi

i am a newbie and want to know why the following code does not take input from the console in perl.

#!/usr/bin/perl -w

print "Name?";
a$= ;
print "Hello";
print $a;
print "\n";

thanks for the help in advance.

Farhan Ali

FredrikN 06-11-2003 06:36 AM

You must read the input with <STDIN> like

$a = <STDIN>;

coolman0stress 06-11-2003 01:53 PM

Yes, you could use <STDIN> for input.

Also, you used a$, when it should've been $a. But, you should avoid using $a (or $b) in general, since these are variables that have special meaning in Perl (for sorting).

A function that will come in handy is 'chomp()', which will remove the newline that is stored in your variable automatically (unless you change the input field seperator). Otherwise you might get into trouble/errors in variable context later on.

For example if you type "123" and press enter ('\n'):
after $a=<STDIN>; $a will store "123\n"
if you then do chomp($a);, $a will now store "123".

It may not seem important right now, but it's very usefull to get rid of the newline character after input.

farhanali 06-12-2003 01:47 PM

thanks guys!

i got it working now...
Farhan Ali

david_ross 06-12-2003 01:59 PM

If you want to actually prompt the user you could use:
Code:

#!/usr/bin/perl

print "What is your name: ";
$name = <>;
print "Hello $name";

exit;


FredrikN 06-12-2003 02:24 PM

Well david_ross , the answer is written twice already

david_ross 06-12-2003 02:26 PM

:P - Half asleep - sorry ;)

FredrikN 06-12-2003 02:27 PM

No problem


All times are GMT -5. The time now is 11:10 PM.