Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re^9: One-liner only checking the first line of the input file

by stevieb (Canon)
on Nov 11, 2015 at 15:56 UTC ( [id://1147474]=note: print w/replies, xml ) Need Help??


in reply to Re^8: One-liner only checking the first line of the input file
in thread One-liner only checking the first line of the input file

I wrote a module a while back that deals with issues exactly like this (where the line-endings are different than your platform). File::Edit::Portable.

Here's an example that reads the file, stores the original line endings, modifies them to the local platforms, then writes your output to a temporary file.

It then writes the modified data into a new file, input.txt.new with the original line endings. You can overwrite the original file by omitting the copy parameter in the write() method. read() can return an array of the entire file in list context instead of a file handle, and write() can accept an array reference of file contents in contents as opposed to a file handle. Only use the array technique if your file is small, as the whole thing will be put into memory.

use warnings; use strict; use File::Edit::Portable; my $rw = File::Edit::Portable->new; my $fh = $rw->read('input.txt'); my $wfh = $rw->tempfile; while (<$fh>){ chomp; my @line = split('\s+', $_); print $wfh "$line[2]\t$line[7]\n" if $line[7] > 0; } $rw->write(copy => 'input.txt.new', contents => $wfh);

Replies are listed 'Best First'.
Re^10: One-liner only checking the first line of the input file
by 1nickt (Canon) on Nov 12, 2015 at 14:36 UTC

    There's also the --output-line-ending flag to perltidy. (See Perltidy).

    $ perltidy -ole=unix foo.pl

    The way forward always starts with a minimal test.

      That's a nice trick :) Regarding my module, its purpose was to dynamically work with any file, regardless of its endings while on any platform, without clobbering the original endings (it effectively loads up the file using the local platform's record separator, and then writes back to a file with the recsep found in the original file).

      Imagine automatically editing 5,000 files where there is a mix of various line endings. My module eliminates the need to even check each file, they will all be written back to orig endings. This was a scenario I ran into with another one of my modules, so I wrote this one to work around the problem.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-03-29 15:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found