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

Re: [MacPerl] Testing for Defined



On Thu, 21 Jan 1999 13:10:50 +0100 (MET), Christian Brechbuehler wrote:

[ I wrote:]
>> this should be an acceptable alternative:
>> 
>> 	while (($the_input = <INPUT>) && defined($the_input)){
>
>Not really.
>
>1. This still produces the same warning (Hint: always use -w !).

With the stress on *run* with -w. I didn't test it. (!!!)

The next *is* an acceptable alternative (tested):

 	while ($the_input = <INPUT>, defined($the_input)){ ... }

(Assignment has a higher precedence than comma; oddly enough.)

Now, as there seems to remain a lot of confusion about this subject,
though it has been tackled time and time again before, so here is some
demo code that shows the danger, and some proposed solutions.

First, create some test files:
#! perl -w
{
	local $\ = "\n";
	open(FILE,'>count');
	 foreach (qw(one two three)) {
		 print FILE;
	 }
}

open(FILE,'>countdown');
print FILE join("\n",reverse (0..3));
__END__

Ok. Here's the basic test script, in which you will be asked to modify
the discussed line.
#! perl -w
# read files
@ARGV = qw(countdown count);
while(<>) {	# replace this code line
	print;
}
__END__

Run it, and you'll see:
3
2
1
0one
two
three

Note that there was no end-of-line appended to the zero, so there won't
be one now, between the last line of the first file, and the first line
of the second file, either.

Replace the indicated code line with:

	while($_ = <>) {

and run it again. Now, you'll see (besides the warning):

3
2
1

And that's it! The final line of the first file will terminate the loop,
the reason being that the string "0" is treated as false, so not only
will you miss that line, but all the lines of all remaining files as
well!
 
You can check that both these replacements work fine:

	while(defined($_ = <>)) {
and
	while($_ = <>,defined) {

You need one of those if you don't use the default assignment to $_.

   HTH,
   Bart.

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