Bryan Harris wrote:
> 
> Yes, I learned about paste today, very handy.  Unfortunately paste doesn't
> always work right...
> 
> t1
> 10  14
> 11  15
> 12
> 13
> 
> t2
> 20  26
> 21  27
> 22
> 23
> 24
> 25
> 
> % paste t*
> 10      14      20      26
> 11      15      21      27
> 12      22
> 13      23
>         24
>         25

The reason paste doesn't work right and why it would be difficult to do the
correct thing in perl is that the files switch from two columns to one column.


> I would think the 22-25 should be lined up under the 21, but it doesn't do
> it like that.  Also, paste has a limit of 12 input files, and I can envision
> cases where we'd need to "paste" ~100 single or double column files of
> different lengths.

Here is one way to do it:

#!/usr/bin/perl
use warnings;
use strict;
use Getopt::Std;
use Tie::File;
use POSIX qw(tmpnam);

my $usage = <<USAGE;

usage: $0 [-o outputfile] file1 file2 ... filen

        -o outputfile
        Print to outputfile instead of standard output

        -h
        Prints this message

USAGE

my %opts;
getopts( 'ho:', \%opts );
die $usage if exists $opts{h};
die $usage unless @ARGV;

my $file = exists $opts{o} ? $opts{o} : tmpnam();

tie my @output, 'Tie::File', $file or die "Cannot open $file: $!";

my ( $total, $gtotal ) = ( 0, 0 );
my @lines;
while ( <> ) {
    next unless /\S/;
    my $count = ( my @fields = split ) + 1;
    $total = $count if $total < $count;
    push @lines, \@fields;

    if ( eof ) {
        for my $i ( 0 .. $#lines ) {
            $output[$i] .= "\t" x $gtotal unless defined $output[$i];

            $output[$i] .= join( "\t", @{$lines[$i]} )
                        . "\t" x ($total - @{$lines[$i]});
            }

        $gtotal += $total - 1;
        $total = 0;
        @lines = ();
        }
    }

for ( @output ) {
    s/\t$//;
    print "$_\n" unless exists $opts{o};
    }

untie @output;
unlink $file unless exists $opts{o};

__END__



John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to