[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Testing for Defined



> MacPerl complained to Richard Gordon:
>> # Value of <HANDLE> construct can be "0"; test with defined().
>
>
> Excerpt of message (sent 19 January 1999) by David Turley:
>> while (defined($the_input = <INPUT>)){
>>
>> This makes sure your while loop won't end prematurly if a line in
>> <INPUT> contains only '0'.
>
> You must set $/="0" to make this happen, or is there another way?

If $/ is left alone, and the file ends with a bare 0 (intended as a 
line containing 0, but with no line ending), then the while 
($the_input = <INPUT>) construct fails to process that last line, 
since the string "0" is false.

It's an unlikely but certainly possible case, and can lead to wrong 
results.  Consider a program to compute the average of a series of 
numbers input one per line.  Given the data

10
20
30
0

with no line ending after the zero, just end of file, the problem 
code will compute an average of 20 (sum 60 divided by 3 lines)...the 
recommended code will compute 15.  Reorder the lines of the file:

10
0
30
20

for example, still with no line ending on the final line, and both 
programs compute 15.

   --John
--
John Baxter   jwblist@olympus.net      Port Ludlow, WA, USA
Give a man a fish and you feed him for a day.  Teach him to fish,
and you get rid of him for the weekend.

***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch