[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Read entire file?



On 12/27/00 10:00, Jim Correia at correia@barebones.com wrote:

> What is the best (fastest, clearest code) to read an entire file into a
> variable?  I want to preserve whatever line endings were in the original
> file so I don't want to read it by lines.  Right now I am reading by
> chunks because I can't seem to find a function that will return the size
> in bytes of the file on disk...

>From perlvar.pod (in Shuck, Go>Predefined variables):

input_record_separator HANDLE EXPR
$INPUT_RECORD_SEPARATOR
$RS     
$/    

The input record separator, newline by default.  Works like awk's RS
variable, including treating empty lines as delimiters if set to the null
string.  (Note: An empty line cannot contain any spaces or tabs.) You may
set it to a multi-character string to match a multi-character delimiter, or
to undef to read to end of file.  Note that setting it to "\n\n" means
something slightly different than setting it to "", if the file contains
consecutive empty lines.  Setting it to "" will treat two or more
consecutive empty lines as a single empty line.  Setting it to "\n\n" will
blindly assume that the next input character belongs to the next paragraph,
even if it's a newline. (Mnemonic: / is used to delimit line boundaries when
quoting poetry.)

            undef $/;
            $_ = <FH>;          # whole file now here
            s/\n[ \t]+/ /g;

Remember: the value of $/ is a string, not a regexp.  AWK has to be better
for something :-) 


-- 
Craig S. Cottingham
craigc@unicom.net
PGP key available from:
<http://pgp.ai.mit.edu:11371/pks/lookup?op=get&search=0xA2FFBE41>
ID=0xA2FFBE41, fingerprint=6AA8 2E28 2404 8A95 B8FC 7EFC 136F 0CEF A2FF BE41



# ===== Want to unsubscribe from this list?
# ===== Send mail with body "unsubscribe" to macperl-request@macperl.org