開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの機能制限無料版、light版)
- Script言語:Perl
『初めてのPerl 第6版』(Randal L. Schwartz, Tom Phoenix, brian d foy 共著、近藤 嘉雪 訳、オライリー・ジャパン、2012年、ISBN978-4-87311-567-2)の5章(入出力)、5.13(練習問題)3を解いてみる。
その他参考書籍
3.
コード(BBEdit)
sample.pl
#!/usr/bin/env perl use strict; use warnings; use utf8; use 5.016; binmode STDOUT, ':utf8'; binmode STDIN, ':utf8'; print "文字列を入力(ctr+Dで終了)\n"; chomp(my @strs = <STDIN>); print "カラム幅を入力: "; chomp(my $cols = <STDIN>); print "1234567890" x ($cols / 10 + 1) , "\n"; for (@strs) { printf "%${cols}s\n", $_; }
入出力結果(Terminal)
$ ./sample.pl 文字列を入力(ctr+Dで終了) hello good-bye カラム幅を入力: 20 123456789012345678901234567890 hello good-bye $ ./sample.pl 文字列を入力(ctr+Dで終了) hello good-bye カラム幅を入力: 50 123456789012345678901234567890123456789012345678901234567890 hello good-bye $ ./sample.pl 文字列を入力(ctr+Dで終了) hello good-bye カラム幅を入力: 25 123456789012345678901234567890 hello good-bye $
ちなみにJavaScriptの場合。
コード(BBEdit)
var strs = [], s = "", result = "", i, max, cols; while (true) { s = prompt("文字列(空白で終了)", ""); if (/^\s*$/.test(s)) { break; } strs.push(s); } cols = parseInt(prompt("カラムの幅を指定", ""), 10); result += new Array( Math.floor(cols / 10) + 2 ).join("1234567890") + "\n"; for (i = 0, max = strs.length; i < max; i += 1) { result += new Array(cols - strs[i].length + 1).join(" ") + strs[i] + "\n"; } $('#pre0').text(result);
pythonの場合。
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- import re strs = [] while True: s = input("文字列(空白で終了)") if re.search(r"^\s*$", s): break strs.append(s) cols = int(input("カラムの幅を指定: ")) print("1234567890" * (cols // 10 + 1)) for s in strs: print("%{0}s".format(cols) % s)
入出力結果(Terminal)
$ ./sample.py 文字列(空白で終了)hello 文字列(空白で終了)good-bye 文字列(空白で終了) カラムの幅を指定: 20 123456789012345678901234567890 hello good-bye $ ./sample.py 文字列(空白で終了)hello 文字列(空白で終了)good-bye 文字列(空白で終了)50 文字列(空白で終了) カラムの幅を指定: 50 123456789012345678901234567890123456789012345678901234567890 hello good-bye 50 $ ./sample.py 文字列(空白で終了)hello 文字列(空白で終了)good-bye 文字列(空白で終了) カラムの幅を指定: 25 123456789012345678901234567890 hello good-bye $
0 コメント:
コメントを投稿