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

Is there any way I can restict the amount of data that I read from a file by setting $/ to "undef". I need to do this because the file may be huge and there is no concept of a paragraph in the file.
  • Comment on Restriction on getting multiline data into a string

Replies are listed 'Best First'.
Re: Restriction on getting multiline data into a string
by BrowserUk (Patriarch) on Nov 19, 2003 at 09:44 UTC

    By setting $/ to a reference to an integer, you can control how many bytes are read in each use of the diamond operator.

    local $/ = \65536; my $scalar = <FILE>; print length $scalar; # prints 65536 (assuming :raw)

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    Hooray!
    Wanted!

      In the risk of stating the obvious, I'd like to point out that this is documented in perlvar (search for the section for "$/"). I recall that this is a fairly new addition to Perl, but at least, it is documented to work for perl 5.005_03. So it's not that recent. :)
      Thanks for the tip below. ++
      local $/ = \65536;
Re: Restriction on getting multiline data into a string
by Roger (Parson) on Nov 19, 2003 at 09:41 UTC
    You can use the sysread function. Try type perldoc -f sysread and read its documentation.

    sysread FILEHANDLE, $scalar, $block_size;
    The idea is to determine the size of the file with seek and tell, and then keep reading $block_size number of characters into the scalar, in a loop, until there is no more input.

      I would suggest using read rather than sysread unless you have a specific reason not to. The main reason being that read cooperates better with other filehandle commands.

      Performance is not a major reason. Performance varies depending on platform and specifics of how you use it. Lots of small calls to sysread should be slower than the same calls to read. On some operating systems and versions of Perl, stdio is slow and so read is slower.