データをいちいち指定しなければならないのは面倒なので、
プログラムに指定しておくことにする。regexp_cutout.rb から
regexp_readdata.rb
を作る。open -- end を用い、ファイルを指定しする。
データを開いて (OPEN) 読み込むのでモードは r
(Read)
である。
#!/usr/koeki/bin/ruby
#coding: euc-jp
STDERR.print("検索パターン : ")
pattern = STDIN.gets.chomp
request = Regexp.new(pattern, true)
open("station.dat","r") do |candidate|
while station = candidate.gets
if request =˜ station
# print station
if /(\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ =˜ station
printf("%s駅\n", $1)
end
end
end
end
実行は
% ./regexp_readdata.rb
だけでよい。
open("ファイル名","モード") do |ファイル変数| : ファイル変数 に対して行う処理 : end
open -- endを一般に File Open と呼ぶ。 ファイル変数は、 open("ファイル名","モード") で開いた場所を教える変数である。