2012年11月27日火曜日

開発環境

『初めてのPerl 第6版』(Randal L. Schwartz, Tom Phoenix, brian d foy 共著、近藤 嘉雪 訳、オライリー・ジャパン、2012年、ISBN978-4-87311-567-2) の4章(入出力)、5.13(練習問題)3を解いてみる。

その他参考書籍

3.

コード(TextWrangler)

sample.pl

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use 5.016;
binmode STDIN, ':utf8';
binmode STDOUT, ':utf8';

print "カラム幅を指定: ";
chomp(my $width = <STDIN>);

print "文字のリストを1行に1個ずつ入力\n";
chomp(my @strings = <STDIN>);

unless($width =~/^\d+$/){
  $width = 0;
  for(@strings){
    $width = length $_ if length $_ > $width;
  }
}

print "1234567890" x ($width / 10 + 1) . "\n";
for(@strings){
  printf "%${width}s\n", $_;
}

入出力結果(Terminal)

$ ./sample.pl
カラム幅を指定: 30
文字のリストを1行に1個ずつ入力
hello
good-bye
1234567890123456789012345678901234567890
                         hello
                      good-bye
$ ./sample.pl
カラム幅を指定: perl
文字のリストを1行に1個ずつ入力
hello
good-bye
1234567890
   hello
good-bye
$

ちなみにJavaScriptの場合。

コード(TextWrangler)

var strings = [];
var str;
var width = prompt("カラム幅を指定", null);
while(true){
  var str = prompt("文字列を入力(空文字で終了)", null);
  if(/^\s*$/.test(str)) break;
  strings.push(str);
}
String.prototype.repeat = function(n){
  var result = "";
  for(var i = 0; i < n; i++){
    result += this;
  }
  return result;
};
if(! /^\d+$/.test(width)){
  width = 0;
  for(var i = 0; i < strings.length; i++){
    if(strings[i].length > width) width = strings[i].length;
  }
}
width = parseInt(width);
var pre = 0;
var result = "1234567890".repeat(Math.floor(width / 10) + 1) + "\n";
for(var i = 0; i < strings.length; i++){
  var pre = width - strings[i].length;
  result += " ".repeat(pre) + strings[i] + "\n";
}
$('#pre0').text(result);



pythonの場合。

sample.py

コード(TextWrangler)

#!/usr/bin/env python3.3
#-*- coding:utf-8 -*-

import re

strings = []
pattern = re.compile(r"^\s*$")
print("文字列のリストを1行に1個ずつ入力(空行で終了)")
while 1:
    s = input()
    if re.match(pattern, s): break
    strings.append(s)

print("1234567890" * 6)
for s in strings:
    print(s.rjust(20))

入出力結果(Terminal)

$ ./sample.py
カラム幅を入力: 30
文字列のリストを1行に1個ずつ入力(空行で終了)
hello
good-bye

1234567890123456789012345678901234567890
                         hello
                      good-bye
$ ./sample.py
カラム幅を入力: python
文字列のリストを1行に1個ずつ入力(空行で終了)
hello
good-bye

pattern
1234567890
   hello
good-bye
$

0 コメント:

コメントを投稿