read is not guaranteed to read the number of bytes you specify, especially when dealing with handles which aren't tied to files. I also added error handling and made the buffer size configurable.

use constant BLK_SIZE => 16*1024; sub pseek { my( $p, $to_read, $blk_size ) = @_; $blk_size ||= BLK_SIZE; while ( $to_read ) { $blk_size = $to_read if $to_read < $blk_size; my $read = read( $p, my $discard, $blk_size ); return $read if !$read; $to_read -= $read; } return 1; }

Update: Or maybe not. My testing shows that read does wait, but its documentation uses the same wording as sysread which does not. As such, I wouldn't count on the observed bahviour.

$ perl -e'$|=1; print "a"; sleep(10); print "b"' | perl -le'read(STDIN +, $buf, 10); print $buf' ab $ perl -e'$|=1; print "a"; sleep(10); print "b"' | perl -le'sysread(ST +DIN, $buf, 10); print $buf' a

Same results on linux and Windows.


In reply to Re^2: seek() functionality on pipes by ikegami
in thread seek() functionality on pipes by HKS

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.