Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Reading in a file not recognizing lines

by bradcathey (Prior)
on May 21, 2006 at 23:14 UTC ( #550836=perlquestion: print w/replies, xml ) Need Help??

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

Fellow Monasterians,

I've done this before, but not often. Normally, this...

open (FILE, "somefile.txt") or die; my @records = <FILE>; close(FILE);

OR

my @records; open (FILE, "somefile.txt") or die; while (<FILE>) { push @records, $_; } close(FILE);

...renders a nice array of one line per element.

Today, the above placed the entire file of 10 lines into one element. I hex-dumped the file and noted the line endings were 0D, but I'm not sure what they should be.

To get it to work, I had to do this...

my @records = split(/\r/,$records);

Has this something to do with how the text file was saved? Thanks!


—Brad
"The important work of moving the world forward does not wait to be done by perfect men." George Eliot

Replies are listed 'Best First'.
Re: Reading in a file not recognizing lines
by Fletch (Bishop) on May 21, 2006 at 23:19 UTC

    Mac OS (well, at least older Mac OS) use(s|d) \x0d to represent end of line, so your file probably came from there or hopped through there without proper translation. You could:

    • re-fetch the file, this time telling whatever mechanism you're using to treat it as a text file (e.g. FTP in ASCII mode)
    • set $/ to \x0D
    • use split as you've done
    • use the *NIX tr utility to translate the line endings
    • use the perl -i -pe equivalent of the above to do the same

    Also: see perlport for the section on "Newlines".

      Fetch, thanks. Great insight: was using an old OS9 program to generate tab-delimited conversion for transport to web.

      Embarrassingly, I've never worked with $/. Thanks for the nudge.


      —Brad
      "The important work of moving the world forward does not wait to be done by perfect men." George Eliot
Re: Reading in a file not recognizing lines
by bobf (Monsignor) on May 22, 2006 at 02:32 UTC
Re: Reading in a file not recognizing lines
by ioannis (Abbot) on May 22, 2006 at 02:31 UTC
    Or use the PerlIO layer. The code bellow is fof MS-DOS files, not sure if a layer exists for OSX.
    use PerlIO ; open F, '<:crlf', 'data' ;
    ;
Re: Reading in a file not recognizing lines
by jesuashok (Curate) on May 22, 2006 at 02:47 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://550836]
Approved by GrandFather
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2022-11-29 07:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?