>> I've tried everything I can think of, but I feel like a 6th grader trying to
>> solve a 7th grade math problem:
>> 
>> I'm trying to build a "pretty-fier" for any tab-delimited text file
>> (basically space-pad the columns so the decimals line up).  I search through
>> the columns finding the longest field with and highest precision level for
>> each column, then create a format string for the printf command.  The guts
>> of it looks like this:
>> 
>> **************************************
>> $formatstr = "";
>> $index = 0;
>> foreach (@lwid) {
>>   $formatstr .= "%$lwid[$index].$lprec[$index]f".'\t';
>>   $index++;
>> }
> 
> In idiomatic perl that would be written as:
> 
> foreach my $index ( 0 .. $#lwid ) {
>   $formatstr .= "%$lwid[$index].$lprec[$index]f\t";
> }

Nice!  I wouldn't have thought to use a foreach on an on-the-spot (?) array
like that.


>> substr($formatstr,-2,2) = "";
>> $formatstr .= '\n';
> 
> Why not use join() instead of adding an extra "\t" and removing it
> later:
> 
> my $formatstr = join( "\t", map "%$lwid[$_].$lprec[$_]f", 0 .. $#lwid )
> . "\n";

Wow.  I would've never thought of that.


> Also, instead of using two arrays for width and precision, it might be
> simpler to use an array of arrays.

Good idea, I wouldn't have thought of that either.


>> open(FILE, ">$file$ext") || die("Couldn't create $file$ext: $!\n");
>> 
>>     foreach (@content) {
>>         @fields = split;
> 
> I assume that you are split()ing the input in order to measure the width
> of each field so you could store the contents in an array of arrays to
> avoid split()ing the data again here.  Also you could pre-format the
> data and avoid this foreach loop altogether.

Yes, absolutely right.


>>         if (@fields) { printf FILE $formatstr, @fields; }
>>         else { print FILE $_; }
>>     }
>> 
>> close(FILE);
>> **************************************
>> 
>> ... but that "printf" spits out actual "\t" and "\n"s.  How can I get the
>> printf to interpret those into tabs and newlines?
> 
> Put escape sequences in double quoted strings, not single quoted
> strings, to have them interpolated properly.

I'll try it.

Thanks for the reply, John, you always manage to clear things up for me.

- Bryan


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to