2013年8月23日金曜日

開発環境

『初めてのPerl 第6版』(Randal L. Schwartz, Tom Phoenix, brian d foy 共著、近藤 嘉雪 訳、オライリー・ジャパン、2012年、ISBN978-4-87311-567-2)の15章(スマートマッチとgiven-when)の15.6(練習問題)1を解いてみる。

その他参考書籍

1.

コード(BBEdit)

sample.pl

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

my $secret_number = int(1 + rand 100);

while (1) {
    chomp(my $guess = <STDIN>);
    given($guess) {
        when (/^\s*$/) { last; }
        when(/\D/ ) { say "数値を入力してください";}
        when($secret_number > $_ ){ say "Too low";}
        when($secret_number < $_ ){ say "Too high"}
        default {
            say "正解!";
            last;
        }
    }
}

入出力結果(Terminal)

$ ./sample.pl

$ ./sample.pl
perl
数値を入力してください
50
Too low
75
Too low
88
Too low
94
Too low
97
正解!
$

ちなみにpython3.3の場合。

コード(BBEdit)

sample.py

#!/usr/bin/env python3.3
## Copyright (C) 2013 by kamimura
#-*- coding: utf-8 -*-

import re, random

secret_num = random.randint(1, 100)

while True:
    guess = input()
    if re.search(r"^\s*$", guess):
        break
    if re.search(r"\D", guess):
        print("数値を入力してください")
    else:
        guess = int(guess)
        if guess < secret_num:
            print("Too low")
        elif guess > secret_num:
            print("Too high")
        else:
            print("正解!")
            break

入出力結果(Terminal)

$ ./sample.py

$ ./sample.py
python
数値を入力してください
50
Too high
24
Too high
11
Too high
5
正解!
$

0 コメント:

コメントを投稿