Strange !exists/foreach/read interaction

B

Bo Lindbergh

use strict;
use warnings;

my($index,@array);

$#array=2;
$index=0;
foreach my $element (@array) {
printf STDERR ("index=%d\n",$index++);
read(DATA,$element,2);
}
print STDERR "array=('",join("','",@array),"')\n";

__DATA__
Random line of text which is irrelevant to the matter.


With either 5.6.1 or 5.8.1, the above program prints this on STDERR:
index=0
index=1
Use of uninitialized value in read at oddity line 10.
index=2
Use of uninitialized value in read at oddity line 10.
array=('Ra','nd','om')


Why does read complain about an output-only parameter being undefined?
And why _doesn't_ it complain on the first iteration of the loop?


/Bo Lindbergh
 
P

Paul Lalli

use strict;
use warnings;

my($index,@array);

$#array=2;
$index=0;
foreach my $element (@array) {
printf STDERR ("index=%d\n",$index++);
read(DATA,$element,2);
}
print STDERR "array=('",join("','",@array),"')\n";

__DATA__
Random line of text which is irrelevant to the matter.


With either 5.6.1 or 5.8.1, the above program prints this on STDERR:
index=0
index=1
Use of uninitialized value in read at oddity line 10.
index=2
Use of uninitialized value in read at oddity line 10.
array=('Ra','nd','om')


Why does read complain about an output-only parameter being undefined?
And why _doesn't_ it complain on the first iteration of the loop?

From perldoc -f read:
read FILEHANDLE,SCALAR,LENGTH,OFFSET

Attempts to read LENGTH characters of data into variable SCALAR from
the specified FILEHANDLE. Returns the number of characters actually
read, 0 at end of file, or undef if there was an error (in the latter
case $! is also set). SCALAR will be grown or shrunk so that the last
character actually read is the last character of the scalar after the
read.

That description seems to imply that $element is not an output-only
parameter. It seems like Perl would have to read the contents of $element
in order to possibly have to shrink it to fit the new size of the incoming
data. That could be the cause of the warning.

(As for why no warning the first time around, I have no idea).

Just my guess. I could be completely wrong.

Paul Lalli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top