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

Hello Monks

I have a text file which size is 12 KB. But I need 1 KB at the beginning.

open FILE, 'c:\space\sp.txt' or die $!; $_=<FILE>; ## It'll store whole text, but i need 1KB only

Please guide me.

Thank

Replies are listed 'Best First'.
Re: Get only 1KB from text File
by gopalr (Priest) on Oct 15, 2005 at 06:13 UTC

    Hi

    User Input Record Separator ($/)

    local $/=\"1024"; open FILE, 'c:\space\sp.txt' or die $!; $_=<FILE>; #<IT WILL READ ONLY 1KB>
      Bear in mind that "local $/..." will only be "local" if it's inside a curly-brace block:
      { local $/=\"1024"; open FILE, 'c:\space\sp.txt' or die $!; $_=<FILE>; #<IT WILL READ ONLY 1KB> } # now $/ is back to its original value # another way (note that quotes are not needed): open FILE, $name or die $!; $_ = do { local $/ = \1024; <FILE> };
      If you miss that little detail, "local" is equivalent to "main".

      But really, just using "read()" seems easier.

Re: Get only 1KB from text File
by Skeeve (Parson) on Oct 15, 2005 at 06:54 UTC

    The "classic" way:

    my $numread= read(FILE, $_, 1024);


    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
Re: Get only 1KB from text File
by saintmike (Vicar) on Oct 15, 2005 at 06:20 UTC
Re: Get only 1KB from text File
by pg (Canon) on Oct 15, 2005 at 17:21 UTC
    use strict; use warnings; open FILE, "<file"; my $string; sysread(FILE, $string, 1024); print length($string);