Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I used the getc() example that is used in the perldoc for getting characters from STDIN. below is the code that I used. Can anyone tell me why this dies when I hit the '0' key as well as how to fix this?
#!/usr/bin/perl system ("stty","-icanon","eol","\01","-echo"); while($_=getc(STDIN)){ print("You Pressed: $_\n"); if (m/q/i){die("Quitting...\n");} }

Replies are listed 'Best First'.
Re: getc() question
by repson (Chaplain) on Jan 10, 2001 at 08:06 UTC
    The problem is that you are testing the truth of $_ which does not tell you if a character was read.

    In perl the false values are 0, "0", "" and undef. If any of these values are returned, you exit the loop, while if you read the docs for getc, the value returned when there are no characters to read is always undef which can be differenciated from the other falses by testing with the defined function instead of basic truth.

    So you want to turn the while line to:
    while( defined($_=getc(STDIN)) ){