tags:

views:

668

answers:

3

So I have a bit of problem figuring what Perl does in the following case:

while(1){
$inputLine=<STDIN>

#parse $inputLine below
#BUT FIRST, I need to check if $inputLine = EOF

}

before I get the obvious answer of using while(<>){}, let me say that there is a very strong reason that I have to do the above (basically setting up an alarm to interrupt blocking and I didnt want that code to clutter the example).

Is there someway to compare $inputLine == undef (as I think that is what STDIN returns at the end).

Thanks.

+9  A: 

Inside your loop, use

last unless defined $inputLine;

From the perlfunc documentation on defined:

defined EXPR
defined

Returns a Boolean value telling whether EXPR has a value other than the undefined value undef. If EXPR is not present, $_ will be checked.

Many operations return undef to indicate failure, end of file, system error, uninitialized variable, and other exceptional conditions. This function allows you to distinguish undef from other values. (A simple Boolean test will not distinguish among undef, zero, the empty string, and "0", which are all equally false.) Note that since undef is a valid scalar, its presence doesn't necessarily indicate an exceptional condition: pop returns undef when its argument is an empty array, or when the element to return happens to be undef.

Greg Bacon
Thank you. I am new to perl, but I am getting the hang of it.
intiha
@intiha You're welcome! We're here to help!
Greg Bacon
+4  A: 
defined($inputLine)

Also, see the 4 argument version of the select function for an alternative way to read from a filehandle without blocking.

mobrule
A: 

You can use eof on the filehandle. eof will return 1 if the next read on FILEHANDLE is an EOF.

Vivin Paliath
From the eof documentation: "(Note that this function actually reads a character and then 'ungetc's it, so isn't very useful in an interactive context.)" The OP is reading from STDIN, i.e., in an interactive context.
Greg Bacon
Ah, I just fixated on the *eof*. On further read, I also noticed that it says you almost never need to use *eof* since you can just look for the *undef*. Funny - I know I've used eof a few times. But I guess TMTOWTDI ;)
Vivin Paliath