strredwolf has asked for the wisdom of the Perl Monks concerning the following question:

How do you determine how much is left to read on a filehandle or socket? I'm trying to improve client-side performance of WSProxy, and right now, I have perl returning stuff by the line in most cases where there's no Content-Length: in a HTTP reply.
  • Comment on Deteriming how much is left to read on a filehandle

Replies are listed 'Best First'.
Re: Deteriming how much is left to read on a filehandle
by redmist (Deacon) on Jun 18, 2000 at 01:05 UTC
    How do you determine how much is left to read on a filehandle or socket?

    Well, according to page 132 of the Camel Book, it says that $. is a special variable that holds "The current input line number of the last filehandle that was read." I assume that you could (if you knew how many lines were in the file) periodically compare $. and the line number of the EOF...just my 2 (newbie) cents.

    redmist
Re: Deteriming how much is left to read on a filehandle
by reptile (Monk) on Jun 18, 2000 at 04:09 UTC

    I've wondered the same thing. First, for filehandles, I know you can use -s HANDLE to return the size of the file. If you use the read to read from the file, it will return the number of bytes read, and you can subtract that from another variable you initially set to the file size. Unfortunately, this (as far as I know) only works for files.

    I've tried something similar on sockets and -s just doesn't return anything unless there's data. If there isn't any, it waits until there is, which could be never. So, to conditionally read from the socket if there was any data on it, I installed an SIGALRM handler to timeout any read operations after 1 second. Of course if I didn't want it to pause that would just totally suck. Anyway, I'm rambling, but I know of no way to check how much data is waiting on a socket. Still, read does return how much data was read from a socket, but someone please correct me if I'm wrong, it will continue to read, or try to read, until it reads either an EOF or however many bytes you tell it to read. Plus you have no way of knowing how many bytes are waiting to be read in the first place, and thus no way to know how much is left.

    I'm going to vote up your node because I really really want an answer to this myself, and for some reason it hasn't landed on the SOPW page yet.

    72656B636148206C72655020726568746F6E41207473754A

      someone please correct me if I'm wrong, it will continue to read, or try to read, until it reads either an EOF or however many bytes you tell it to read

      If your platform supports it, you can use fcntl to set the O_NONBLOCK flag on a socket, which will make read return even if it was not able to read as many bytes as you tell it to read.