Name

read

Synopsis

read filehandle, $var, length, [offset]

Attempts to read length bytes of data into variable var from the specified filehandle. The function returns the number of bytes actually read, or 0 at end-of-file. It returns the undefined value on error. var will grow or shrink to the length actually read. The offset, if specified, says where in the variable to start putting bytes, so that you can do a read into the middle of a string.

To copy data from the filehandle FROM into the filehandle TO, you could say:

while (read FROM, $buf, 16384) {
    print TO $buf;
}

Note that the opposite of read is simply print, which already knows the length of the string you want to write and can write a string of any length.

Perl’s read function is actually implemented in terms of standard I/O’s fread function, so the actual read system call may read more than length bytes to fill the input buffer, and fread may do more than one system read to fill the buffer. To gain greater control, specify the real system call using sysread.

Get Perl in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.