変換スクリプト

今後も結構使いそうにつき。

#!/usr/bin/env perl

# tabular:
# 改行区切りのレコードを tex の tabular に変換。
# 大きくなりすぎたら自動的に改ページしたりはできない。

use Getopt::Std;
use warnings;
use strict;

my (%opt, @body);
getopts('dfbn:p:',\%opt);
usage() if (not exists($opt{n}) or (not exists($opt{p})));

my ($fmt, $ln_delim, $frame, $b_doc, $e_doc) = ("", "", "", "", "");
$fmt = &getfmt();
$ln_delim = q(\hline) if (exists $opt{b});
$frame = q(\hline) if (exists $opt{f});
$b_doc = q(\documentclass{jarticle}
\begin{document}) if (exists $opt{d});
$e_doc = q(\end{document}) if (exists $opt{d});

my @input = <STDIN>;
foreach(@input){
  chomp;
  s/%/\\%/;
  s/&/\\&/;
  s/\\/\$\\backslash\$/;
}

while (@input){
  my @cur = splice(@input, 0, $opt{n});
  #端数の処理未実装
  local $" = " & ";
  push (@body, "@cur");
}

local $" = " \\\\$ln_delim\n";

print "$b_doc
\\begin{tabular}{$fmt}$frame
@body \\\\
$frame\\end{tabular}
$e_doc
";

sub getfmt {
  my @tmp;
  local $" = (exists $opt{b}) ? "|" : "";
  push(@tmp, $opt{p}) foreach (0 .. ($opt{n} -1));
  $fmt = "@tmp";
  $fmt = "|" . $fmt . "|" if (exists ($opt{f}));
}

sub usage {
  print <<USAGE;
  Usage: $0 -p {l|c|r} -n ## [-bfd] < input_file
    -p: horizontal positions of values
    -n: # of columns
    -b: prints cell-borders
    -f: prints frames
    -d: prints [\begin|\end]{document}
USAGE
  exit (1);
}