Created
February 13, 2016 05:34
-
-
Save tsucchi/6d3327685c4cf98a2375 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
# 引数が数値A 演算子 数値Bという文字列であれば、その式を計算して結果を返す関数calc_stringを書いてみましょう | |
# 「数値A」「演算子」「数値B」の間にはそれぞれ半角スペースが入ります | |
# 数値は正・負の整数とし、演算子は+-*/%が使えるものとします | |
# 引数が 数値A 演算子 数値B というフォーマットに一致しない場合は ERROR! という文字列を返すようにしましょう | |
print calc_string("-12 + 34"); | |
sub calc_string { | |
my ($input) = @_; | |
my ($value_a, $operator, $value_b) = split /\s+/, $input; | |
if ( !defined $value_a || !defined $operator || !defined $value_b ) { | |
return 'ERROR!'; | |
} | |
if ( $value_a !~ /^[+-]?\d+$/ || $value_b !~ /^[+-]?\d+$/ ) { | |
return 'ERROR!'; | |
} | |
if ( $operator eq '+' ) { | |
return $value_a + $value_b; | |
} | |
elsif ( $operator eq '-' ) { | |
return $value_a - $value_b; | |
} | |
elsif ( $operator eq '*' ) { | |
return $value_a * $value_b; | |
} | |
elsif ( $operator eq '/' ) { | |
return $value_a / $value_b; | |
} | |
elsif ( $operator eq '%' ) { | |
return $value_a % $value_b; | |
} | |
return 'ERROR!'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment