l2c.pl – Lines to Columns

Here is a little perl script I wrote some time back for converting a text file’s contents from lines to columns.

I’d like to present this script and then psuedo-challenge other visitors of this site to write a more efficient algorithm in the language of their choice. Unfortunately, any way (that I know of) for measuring the efficiency of two or more algorithms across different languages is going to be skewed due to differences in efficiency of compilers, interpreters and what not.

The script converts a file in the format:

1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 19 19 20

to:

1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
10 20

I should add that the program must be able to handle unequal number of items in each line, too.

#!/usr/bin/perl
#
# l2c.pl - lines to columns
#
# http://techslaves.org/
 
# variables
my @lines;
my @columns;
my $iter = 0;
my $linesize = 0;
 
# if num of command line arguments is 2
if (($#ARGV + 1) == 2) {
 
  # open input file for reading
  open(INFILE, $ARGV[0]);
 
  # read input file into an array of arrays
  # an array of "lines" and each "line" is an array of it's "elements" (based on space or tab)
  while()  { push @lines, [ split(/\s+/, $_) ]; }
 
  # close input file
  close(INFILE);
 
  # find the longest line (so we know how many times to loop below)
  foreach $line (@lines) {
    if(@$line > $linesize) { $linesize = @$line; }
  }
 
  # open output file
  open(OUTFILE, ">$ARGV[1]");  
 
  # $iter = line element counter
  # loop while the line element counter is less than the longest line
  while ($iter < $linesize) {
    # loop through every line in the array of lines
    foreach $line (@lines) {
      # if a line element at position $iter exists...
      if( @$line->[$iter] ) {
        # print the line element + a tab to the output file
        print OUTFILE @$line->[$iter], "\t";
      }
      # advance the line element counter
    } $iter++; print OUTFILE "\n";
  }
 
  # close output file
  close(OUTFILE);
 
# if num of command line arguments is NOT 2 print usage
} else { print("usage: $0 inputfile outputfile\n"); }

Leave a Reply

Your email address will not be published. Required fields are marked *