プログラムの比較


本当は、エディタの置換で簡単にできるんだけど・・・。


とりあえず、PerlRubyPythonでテキストファイル中の該当した箇所を置換し、別ファイルに書き込むプログラムを書いてみた。慣れていない部分もあるので、おそらく、本当は、もっと簡単にできるのだろうけど・・・。


今回は、hoge.txtの内容を以下の条件で置換し、その結果をhogehoge.txtに書き出すプログラムをPerlRubyPythonで書いてみた。

  • 新旧のバージョン番号を入力するための入力画面を表示する。
  • hoge.txtの「old」には、古いバージョン番号、「new」には、新しいバージョン番号を置換して、hogehoge.txtに書き出す。
#! /usr/local/bin/perl
#********************************************************
# 置換プログラム (Perl版)
#********************************************************

# コンソール表示部

print "古いバージョンの番号を入力して[Enter] を押してください。\n";

$old = <STDIN>;
chomp $old;

print "新しいバージョンの番号を入力して[Enter] を押してください。\n";

$new = <STDIN>;
chomp $new;

# ファイル処理部

open (IN,"hoge.txt") || die "ファイルが見つかりませんでした。";
open (OUT,">hogehoge.txt");

while(<IN>){
	s/new/$new/g;
	s/old/$old/g;
	print OUT;
}

close IN;
close OUT;
#!/usr/bin/ruby
#********************************************************
# 置換プログラム (Ruby版)
#********************************************************


# コンソール表示部

print "古いバージョンの番号を入力して[Enter] を押してください。\
n";
old = $stdin.gets
old.chop!

print "新しいバージョンの番号を入力して[Enter] を押してください。\n";
new = $stdin.gets
new.chop!

# ファイル処理部

infile = open("hoge.txt")
outfile = open("hogehoge.txt","w")

while infile.gets
	gsub("old",old)
	gsub("new",new)
	outfile.print
end

infile.close
outfile.close
#! /usr/bin/env python
# -*- coding: Shift_JIS -*-
#********************************************************
# 置換プログラム (Python版 その1)
#********************************************************


# コンソール表示部

old = raw_input("古いバージョンの番号を入力して[Enter] を押してください。")
new = raw_input("新しいバージョンの番号を入力して[Enter] を押してください。")

# ファイル処理部

infile = open(r"hoge.txt")
outfile = open(r"hogehoge.txt", "w")

for line in infile.readlines():
	line = line.replace("old",old)
	line = line.replace("new",new)
	outfile.write(line)

infile.close()
outfile.close()
#! /usr/bin/env python
# -*- coding: Shift_JIS -*-
#********************************************************
# 置換プログラム (Python版 その2)
#********************************************************
import re

# コンソール表示部

old = raw_input("古いバージョンの番号を入力してEnterを押してください。")
new = raw_input("新しいバージョンの番号を入力してEnterを押してください。")

# ファイル処理部

infile = open(r"hoge.txt")
outfile = open(r"hogehoge.txt", "w")

for line in infile.readlines():	
	line = re.sub("old",old,line)
	line = re.sub("new",new,line)
	outfile.write(line)

infile.close()
outfile.close()


PerlRubyでは、以下の処理をするだけをすると、文字列を文章に挿入する際に改行コードまで入力されてしまう。

# * Perl *

$old = <STDIN>;
# * Ruby *

old = $stdin.gets


そのため、改行コードを削除する必要があるため、以下の処理を追加した。

# * Perl *

chomp $old;
# * Ruby *

old.chop!


ちなみに、Pythonでは、問題なく処理できた。


ActivePerl
http://www.activestate.com/Products/ActivePerl/


One-Click Ruby Installer
http://rubyinstaller.rubyforge.org/wiki/wiki.pl


Python 日本語環境用インストーラ(Win32)
http://www.python.jp/Zope/download/pythonjpdist