Peter Xu wrote:
Hi, everyone,
Hello,
I've met some problem while practice my perl. It seems that in some
condition,
sysread() doesn't work?
codes here:
--------------------------------------------
#!/usr/bin/perl -w
use strict;
$| = 1;
open my $file, "<", "test.txt" or die;
## if these add these 2 lines, sysread doesn't work ?
## my $first_line = <$file>;
## print "first_line is : $first_line";
my $ctr = 0;
while(1){
my ($data, $ret);
$ret = sysread $file, $data, 1;
last if $ctr ++ >= 20;
print "ret : $ret, data : ", unpack("H2", $data), "\n";
}
--------------------------------------------
and file "test.txt":
--------------------------------------------
line1
line2
--------------------------------------------
and the output is:
--------------------------------------------
ret : 1, data : 6c
ret : 1, data : 69
ret : 1, data : 6e
ret : 1, data : 65
ret : 1, data : 31
ret : 1, data : 0d
ret : 1, data : 0a
ret : 1, data : 6c
ret : 1, data : 69
ret : 1, data : 6e
ret : 1, data : 65
ret : 1, data : 32
ret : 0, data :
ret : 0, data :
ret : 0, data :
ret : 0, data :
ret : 0, data :
ret : 0, data :
ret : 0, data :
ret : 0, data :
--------------------------------------------
which is thought to be correct.
*My question is*: when I unquote the two lines in the code (which I
think should put the first line["line1\n\r"] into $first_line, and
sysread will only get the second line), sysread() cannot get anything.
perldoc -f sysread
sysread FILEHANDLE,SCALAR,LENGTH,OFFSET
sysread FILEHANDLE,SCALAR,LENGTH
Attempts to read LENGTH bytes of data into variable SCALAR
from the specified FILEHANDLE, using the system call
read(2). It bypasses buffered IO, so mixing this with other
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
kinds of reads, "print", "write", "seek", "tell", or "eof"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
can cause confusion because the perlio or stdio layers
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
usually buffers data. Returns the number of bytes 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 byte actually read is the last byte
of the scalar after the read.
You want to use read instead:
perldoc -f read
John
--
Those people who think they know everything are a great
annoyance to those of us who do. -- Isaac Asimov
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/