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

Hello gurus! I'm in the middle of trying to figure out how to pad variable length documents into fixed length documents. I would like to fix the length based on the longest line in the document. Unix used the CAT function but now everything is "win32" Any ideas? thanks

Replies are listed 'Best First'.
Re: padding variable length documents
by Caillte (Friar) on May 16, 2001 at 18:43 UTC

    You can pad each line out to a fixed length with sprintf. The following makes a string 70 characters long if <= 70 characters to:

    while(<INPUT>) { push @array = sprintf "%70s", $_; }

    $japh->{'Caillte'} = $me;

Re: padding variable length documents
by clintp (Curate) on May 16, 2001 at 18:44 UTC
    If you're asking how to take a file and pad all of the lines out to the same width, this piece might work for you (untested):
    #!/usr/bin/perl -w open(FILE, "+</tmp/foo.txt") || die "Can't open: $!"; $l=0; @lines=map { chomp;$l=$l<length()?length():$l;$_ } <FILE>; seek(FILE, 0, 0) || warn "Seek: $!"; for(@lines) { printf FILE "%-${l}s\n", $_; }
      this is what I have so far but it still doesn't work #!/usr/bin/perl my $maxlength = 80; my $wordlength; my $bufferlength; open(FILE, ">padthis.txt") or die "cant open $!"; while (<>){ chomp; @array = split (" ", $_); foreach $word (@array){ $wordlength = length($word); } $bufferlength = $maxlength - $wordlength; print $bufferlength; #for ($buff = 0; <= $bufferlength; $buff++); for ($i=0;$i<=$bufferlength; $i++) { foreach $word (@array) { print ($word = $word + "*"); print FILE; } } } close FILE;
Re: padding variable length documents
by AidanLee (Chaplain) on May 16, 2001 at 18:35 UTC
    so what you're asking isn't to make all the documents the same length but to make the lines in a document all the same length? I'm a bit confused, otherwise, what the length of a line has to do with the length of the file it is in.

    update: ps: what would you want to pad the documents with? whitespace?