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

I have a file in which i have following entries.
A1 9198 B1 C1 D1 E1 F1 23 232 233 G1 H1 I1 2222 323
I would like the output to be of format
A1,b1,c1,d1,e1,f1,g1,h1,i1 9198,23,232,,,233,2222,,323
I have many lines for A1, A2, ......An. How can this be done?

Replies are listed 'Best First'.
Re: help required on modifying a file content
by ikegami (Patriarch) on Nov 17, 2005 at 07:14 UTC
    use strict; use warnings; my @hdr; my @val; for (;;) { my $hdr_line_in = <DATA>; last unless defined $hdr_line_in; my $val_line_in = <DATA>; last unless defined $val_line_in; chomp($hdr_line_in, $val_line_in); while ($hdr_line_in =~ /(\S+)/g) { my $hdr = lc($1); my $skip = $-[1]; my $val = $val_line_in =~ /^.{$skip}(\S*)/ ? $1 : ''; push(@hdr, $hdr); push(@val, $val); } last unless defined <DATA>; } print(join(',', @hdr), "\n"); print(join(',', @val), "\n"); __DATA__ A1 9198 B1 C1 D1 E1 F1 23 232 233 G1 H1 I1 2222 323
    outputs
    a1,b1,c1,d1,e1,f1,g1,h1,i1 9198,23,232,,,233,2222,,323

    I assumed the data contained spaces, not tabs.

      Thanks for the reply. But in the code i have given only one unit. i.e. A1-I1 is one unit. There are many such units like A2-I2, A3-I3. required formatted text is one below the other. i.e. A1-I1 occupies 6 lines, A2-I2 occupies from 4-l2 lines,and so on. How can I make the code repetitive for every unit. Thanks in advance
        use strict; use warnings; my @hdr; my @val; for (;;) { my $hdr_line_in = <DATA>; last unless defined $hdr_line_in; my $val_line_in = <DATA>; last unless defined $val_line_in; chomp($hdr_line_in, $val_line_in); while ($hdr_line_in =~ /([^\s\d]+(\d+))/g) { my $hdr = lc($1); my $row = $2; my $skip = $-[1]; my $val = $val_line_in =~ /^.{$skip}(\S*)/ ? $1 : ''; push(@{$hdr[$row]}, $hdr); push(@{$val[$row]}, $val); } last unless defined <DATA>; } foreach my $row (0..$#hdr) { next unless defined $hdr[$row]; print(join(',', @{$hdr[$row]}), "\n"); print(join(',', @{$val[$row]}), "\n"); } __DATA__ A1 9198 B1 C1 D1 E1 F1 23 232 233 G1 H1 I1 2222 323 A2 B2 1234 5678
        outputs
        a1,b1,c1,d1,e1,f1,g1,h1,i1 9198,23,232,,,233,2222,,323 a2,b2 1234,5678
Re: help required on modifying a file content
by murugu (Curate) on Nov 17, 2005 at 08:26 UTC
    Hi Bharath,

    Assuming that data given are splitted by space rather than tab's, Here is my try.

    use strict; use warnings; my @result; while (<DATA>) { s/\s*$//; my $line = $_; if (m/[A-Z]/){ my $next_line = <DATA>; while (m/^|\s+/g){ my $pos = pos; my ($key)=$line=~/^.{$pos}(\S+)/; my $value; if ($next_line=~/^.{$pos}(\s+)/) { $value=""; } else { ($value)=$next_line=~/.{$pos}(\S+)/; } push @result,[$key,$value]; } } } @result = sort {$a->[0] cmp $b->[0]} @result; print join ',', map {$_->[0]}@result; print join ',', map {$_->[1]}@result; __DATA__ A1 9198 B1 C1 D1 E1 F1 23 232 233 G1 H1 I1 2222 323

    Regards,
    Murugesan Kandasamy
    use perl for(;;);