#!/usr/bin/perl use warnings; use strict; use Getopt::Long; use constant USAGE =>< [infile [outfile]] DESCRIPTION: This script adds a column to a column file specified by an arithmetic string Eg. '\$2 - \$1 / 2' OPTIONS: --help Prints this help. --seperator Specifies column seperator. EXAMPLES: cat file.tbl | addcolumn.pl '(\$17 - \$3) * \$5 - 4' > newfile.tbl addcolumn.pl --seperator ',' '(\$17 - \$3) * \$5 - 4' file.tbl newfile.tbl AUTHOR: Kasper Munch COPYRIGHT: This program is free software. You may copy and redistribute it under the same terms as Perl itself. END my $help = 0; my $seperator = "\t"; my $ascolumn = 0; my $replace = 0; GetOptions( "help" => \$help, "replace" => \$replace, "seperator=s" => \$seperator, "ascolumn=i" => \$ascolumn ) or die USAGE; $help and die USAGE; my $arithmetic = shift @ARGV or die USAGE; $arithmetic =~ s/\$([0-9]+)/\$c[$1 - 1]/g; @ARGV = ('-') unless @ARGV; my $input = shift @ARGV; open my $in, "$input" or die "$input: $!\n"; @ARGV = ('>&STDOUT') unless @ARGV; my $output = shift @ARGV; open my $out, ">$output" or die "$output: $!\n"; while (my $line = <$in>) { next if $line =~ /^(\#|\$)/; my @c = split /\s+/, $line; chomp $line; my $result = eval $arithmetic; defined $result or die "New column '$arithmetic' could not be calculated"; my @n = (); if ($ascolumn != 0) { @n = (); if ($ascolumn > 1) { @n = @c[0..$ascolumn-2]; } push(@n, $result); push(@n, @c[$ascolumn-1+$replace..$#c]); } else { @n = @c; push(@n, $result); } my $newline = join($seperator, @n); print $out $newline, "\n"; } =head1 SYNOPSIS: addcolumn.pl [OPTIONS] [infile [outfile]] =head1 DESCRIPTION: This script adds a column to a column file specified by an arithmetic string Eg. '$2 - $1 / 2' =head1 OPTIONS: =over 4 =item --help Prints this help. =item --seperator Specifies column seperator. =back =head1 EXAMPLES: cat file.tbl | addcolumn.pl '($17 - $3) * $5 - 4' > newfile.tbl addcolumn.pl --seperator ',' '($17 - $3) * $5 - 4' file.tbl newfile.tbl =head1 AUTHOR: Kasper Munch =head1 COPYRIGHT: This program is free software. You may copy and redistribute it under the same terms as Perl itself. =cut