On Wed, Apr 25, 2012 at 08:52:52AM -0400, Paul Clark wrote:
> Hi All,
> 
> I have a small project that is stumping me aside from using a straight brute 
> force.
> 
> I am processing output from an accounting program that is producing some 
> sort of printer control for some 3rd party print processing.   I have 
> several partial lines that have commands to "over write" the line to create 
> bold type.    I need combine the lines:
> 
> 1            Balance Due:
> 0            Balance Due:            $567.23
> 0                                    $567.23       Before Due Date:
> 0                                                  Before Due Date:   06/15/12
> 0                                                                     06/15/12
> 
> So the output line should be:
> 
>              Balance Due:            $567.23        Before Due Date: 06/15/12
> 
> 
> The problem is the lines can be variable so I cannot just use substr to copy 
> parts of lines.   The brute force was I was going to use is to just create 
> an output array for the line and loop through each line position by position 
> and if the character was not a space, set that position in the output array 
> to the character in the input line.
 
> Any suggestions for a more elegant solution?

Depending on how loosely you define elegent....

#!/usr/bin/perl
use strict;
use warnings;

my %lines;
my $start = <DATA>;
my $line_count;
my $max_len = 0;
while(<DATA>) {
    $max_len = length $_ > $max_len  ? length $_ : $max_len;
    chomp;
    s/\s+$//;
    $line_count++;

    m/(\s[^\s])/;
    my $initial_char = $1;
    my $offset = index $_, $initial_char, 1; # 1 to skip the 1/0 at start of 
line
    my $length = length $_;
    $length -= $offset;
    my $string = substr $_, $offset, $length;

    $lines{$line_count } = [ $offset, $length, $string];

}

my $output = " " x $max_len;
foreach my $i ( sort keys %lines ) {
    my ($offset, $length, $str)  = @{$lines{$i}};
    # print "$offset, $length, $str\n";
    if( $str) {
       substr $output, $offset, $length, $str;
    }
    # print $output,$/;
}
print $output,$/;

__DATA__
1            Balance Due:
0            Balance Due:            $567.23
0                                    $567.23       Before Due Date:
0                                                  Before Due Date:   06/15/12
0                                                                     06/15/12


Clean up and elegence left as an exercise for the reader

-- 
            Michael Rasmussen, Portland Oregon  
      Other Adventures: http://www.jamhome.us/ or http://westy.saunter.us/
Fortune Cookie Fortune du courrier:
Mirrors should reflect a little before throwing back images.
        ~  Jean Cocteau

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to