2008.6.30  

Perlをはじめて1週間目の頃の課題を公開 – calc.pl  

今見たら恥ずかしくて死にそうなのですが、ファイルを整理していたら見つけたのでうp。

1週間の間、毎朝5分以内でFIzzBuzz、JSONの読み込みのプログラムをそれぞれ書いていました。

当時はvimを使ったばかりで、当時の上司に「無理に使うのは大変だったら、テキストエディタでもいいよ」と言われ

半分意地になって「いえ、vimを早く覚えます!!」 と言って教えてもらっていたのが印象に残っています。

while(my $line = <>){ で、キーボードで入力された1行ずつを$lineに代入しループさせている。

<>が標準入力のSTDIN(キーボード入力)を省略していることは完成してから知ったと思う。

・サブルーチン作成時のルール、作り方もこの時初めて知ったと思う。

1回目の入力時・・・数字

2回目の入力時・・・演算子(+,-など)

3 回目の入力時・・・数字

で結果が出るようになっています。

use Smart::Comments は必要に応じて使ってください。

calc.pl

[sourcecode language=’php’]
#!/usr/bin/perl
use strict;
use warnings;

my $num1 = undef;
my $op = undef;
my $num2 = undef;

while(my $line = <>){
chomp $line;

if(not defined $num1){
if(not is_num($line)){
print STDERR “invalid left value($line)”;
next;
}
$num1 = $line;
} elsif(not defined $op){
if(not is_op($line)){
print STDERR “invalid operator value($line)”;
next;
}
$op = $line;
} elsif(not defined $num2){
if(not is_num($line)){
print STDERR “invalid right value($line)”;
next;
}
$num2 = $line;
print eval “$num1$op$num2\n”;

$num1 = undef;
$op = undef;
$num2 = undef;

} else {
die ‘invalid command.’ if(0);
}

last if ($line eq ‘exit’ or $line eq ‘EXIT’);
}
sub is_num{
my ($val) = @_;
## $val
return $val =~ m{\d+};
}

sub is_op{
my ($val) = @_;
## $val
return $val =~ m{\+|-|\*|/};
}
[/sourcecode]

0 Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License.
(c) 2024 Heart Beat | powered by WordPress with Barecity