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

Write padded output without newline

by firmament (Novice)
on Mar 06, 2013 at 12:20 UTC ( #1022001=perlquestion: print w/ replies, xml ) Need Help??
firmament has asked for the wisdom of the Perl Monks concerning the following question:

Brain cramp after a large number of tries.
I want to read a cr/lf terminated file line by line and write each line as 200 bytes left justified and padded with blanks to another file, that is no newlines in the outfile. You can see below what I have at the moment.
The output is not very near what I want:
Line #1: left justified, trailing blanks removed, i.e. _not_ 200 bytes wide
subsequent lines: right justified, padded with blanks, 200 bytes wide.
As mentioned, I donít want a newline at all. And itís not very nice that the first line is printed differently than all the others.

Suggestions?
open (INFILE, "<", $infile) or die $!; open (OUTFILE, ">:raw", $outfile) or die $!; while ( <INFILE> ) { chomp; printf OUTFILE '%-200s', $_; } close INFILE; close OUTFILE;

Comment on Write padded output without newline
Download Code
Re: Write padded output without newline
by daxim (Chaplain) on Mar 06, 2013 at 12:37 UTC
    You forgot the input layer. This works:
    use strictures; use autodie qw(:all); my $infile = 'crlf.txt'; my $outfile = 'out.txt'; open my $in, '<:crlf', $infile; open my $out, '>:raw', $outfile; while (<$in>) { chomp; printf {$out} '%-200s', $_; } close $in; close $out;
    Edit: add hexdumps
      Thanks for your time and help, excellent! Will have plenty of use for this.
Re: Write padded output without newline
by RichardK (Priest) on Mar 06, 2013 at 12:59 UTC

    If printf is being tricky then you could use x instead

    print OUTFILE $_,' ' x (200 - length($_));

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2014-07-23 02:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (131 votes), past polls