Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

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.

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

Replies are listed 'Best First'.
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 (Parson) 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?

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2016-09-30 22:59 GMT
Find Nodes?
    Voting Booth?
    Extraterrestrials haven't visited the Earth yet because:

    Results (574 votes). Check out past polls.