Home > Archive > PERL Miscellaneous > May 2004 > Strange !exists/foreach/read interaction
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Strange !exists/foreach/read interaction
|
|
| Bo Lindbergh 2004-05-18, 3:42 pm |
| 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
| |
| Paul Lalli 2004-05-18, 3:42 pm |
| On Tue, 18 May 2004, Bo Lindbergh wrote:
> 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
|
|
|
|
|