バックスラッシュを¥に変える

スクリプトを,書きました.参考にしたのは,昨日コードリーディングをしたwc.rb.使い方は,入力ファイルと出力ファイルをコマンドラインの引数で指定するだけ.オプションは,-sで結果を出力ファイルではなく標準出力に,-oで,入力ファイルは読み込まずに,出力ファイルだけを指定.なお,出力ファイル名が指定されていない時は,hoge.outになります.以下,ソースです.


#! /opt/local/bin/ruby

def usage
STDERR.print "usage: #{$0} [-so] [infile] [outfile]¥n"
STDERR.print "-s display result by standard output.¥n"
STDERR.print "-o set outfile only.¥n"
exit 1
end

usage if ARGV.size == 0

opt_stdout = false
opt_outfile = false

while ARGV[0] =~ /^-/
$_ = ARGV.shift
opt_stdout = true if ~/s/
opt_outfile = true if ~/o/

usage if ~/[^-so]/
end

if opt_outfile
outfile_name = ARGV.size > 0 ? ARGV.shift : "hoge.out"
outfile = File.open(outfile_name,"w")
elsif !opt_stdout
outfile_name = ARGV.size > 1 ? ARGV[1] : "hoge.out"
outfile = File.open(outfile_name,"w")
end

gets(nil)
out = gsub(/¥¥/,"¥")

if opt_stdout
puts out
end
if opt_outfile
outfile.puts out
elsif !opt_stdout
outfile.puts out
end

outfile.close if !opt_stdout

gsubしてる部分は,前の¥¥をバックスラッシュ*2に変更してください:-)


正直,長過ぎ.Rubyなんだからもうチョット短く出来そう.だって,実際にお仕事してる部分はgsubだけだもの.無駄なオプション付けるから駄目なんだなぁ.本当は入力ファイルが実際に存在するか,とかステータス見ないといけないんだろうけど,個人で使う範囲だから許しておくれ.