Reputation: 319
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.
Upvotes: 5
Views: 18406
Reputation: 1
The following will have problems with input files that have lines which only have a line feed or as in the case that was giving me problems a FF at the beginning of some lines (Form Feed - the file was the output from a program developed at the end of the 70s and still has formatting for a line printer and is still in FORTRAN - I do miss the wide continous paper for drawing flow diagrams on the back).
open (SIMFIL, "<", 'InputFileName') or die "Can´t open InputFileName\n" ;
open (EXTRDATS, ">>", 'OutputFileName' ) or die "Can´t open OutputFileName\n";
$Simfilline = "";
while (<SIMFIL>) {
$Simfilline = <SIMFIL>;
print EXTRDATS $Simfilline;
$Simfilline = <SIMFIL>;
print EXTRDATS $Simfilline;
}
close SIMFIL;
close EXTRDATS;
` The following is when eof comes in handy - the expression: "while ()" can return false under conditions other than the end of the file.
open (SIMFIL, "<", 'InputFileName') or die "Can´t open InputFileName\n" ;
open (EXTRDATS, ">>", 'OutputFileName' ) or die "Can´t open OutputFileName\n";
$Simfilline = "";
while (!eof SIMFIL) {
$Simfilline = <SIMFIL>;
print EXTRDATS $Simfilline;
$Simfilline = <SIMFIL>;
print EXTRDATS $Simfilline;
}
close SIMFIL;
close EXTRDATS;
This last code fragment appears to duplicate the input file exactly.
Upvotes: 0
Reputation: 139491
Inside your loop, use
last unless defined $inputLine;
From the perlfunc documentation on defined
:
defined EXPR
definedReturns 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 distinguishundef
from other values. (A simple Boolean test will not distinguish amongundef
, zero, the empty string, and"0"
, which are all equally false.) Note that sinceundef
is a valid scalar, its presence doesn't necessarily indicate an exceptional condition:pop
returnsundef
when its argument is an empty array, or when the element to return happens to beundef
.
Upvotes: 11
Reputation: 95518
You can use eof on the filehandle. eof will return 1 if the next read on FILEHANDLE is an EOF.
Upvotes: 1
Reputation: 118605
defined($inputLine)
Also, see the 4 argument version of the select
function for an alternative way to read from a filehandle without blocking.
Upvotes: 4