日 | 月 | 火 | 水 | 木 | 金 | 土 |
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |
文字サイズ変更:



トップページ > Perlについて
●Perlについて●
2023-11-30 05:57:29良いコードについて:2023-02-4

さて、プログラミングでの良いコードについての記事を見つけました。
それはPythonで書かれたコードなので、Perlに書き直して、記事と合わせて載せたいと思います。
良いコードについて:2023-02-3の続きになります。
total_price4.pmという、モジュールを書いて半年以上経過してしまいました。
あれから、Perlのやり方でスッキリともっと書けないものかなぁ、と思案しまして。
そして、進化させて書いてみたのが下のコードです。
# total_price5.pm
package total_price5;
use strict;
sub new {
my $class = shift;
my $self = {
'total_price' => my $total_price
};
return bless $self, $class;
}
sub item {
my @item_list = @_;
my @item_list2 = ();
my @rec = ();
foreach(@item_list){
@rec = split(',', $_);
my $hash_lef = {};
$hash_lef->{type} = $rec[0];
$hash_lef->{hinmei} = $rec[1];
$hash_lef->{price} = $rec[2];
if($rec[0] eq 'item'){ # item
$hash_lef->{tax} = 0.08;
}elsif($rec[0] eq 'book'){ # book
$hash_lef->{tax} = 0.01;
}else{
$hash_lef->{tax} = 0.1; # food(defult)
}
push(@item_list2, $hash_lef);
}
return @item_list2;
sub price_with_tax {
my @item_info2 = @_;
my $price = 0;
my $total_price = 0;
foreach my $item(@item_info2){
$price = $item->{price} * (1 + $item->{tax});
$total_price = $total_price + $price;
}
return $total_price;
}
}
sub total_price {
my @item_info = @_;
return &price_with_tax(@item_info);
}
my @syohin_list = ("food,anpan,100", "food,anpan,100", "item,pen,200", "book,jisyo,1000");
my @syohin_info = ();
my @item_list3 = &item(@syohin_list);
my $price = &total_price(@item_list3);
print "Total:$price yen\n";
1;
※カンマ(,)を全角で表示しています。
※見えない部分は、パソコン版は右へ、モバイル版は左へスライドしてください。
合計金額は、1446円です。
サブルーチンitemに商品情報を一括で取得できるようにしました。
サブルーチンprice_with_taxは、サブルーチンtotal_priceに統合しようかと思いましたが、これまで趣旨の流れに反するので、そのままに留めました。
※実際にコードをテストする場合、コピー&ペーストした後、カンマ(,)を半角に戻してください。
Print
Twitter(test)
short URL
いいね:3 back to the TOP |
![]() |
![]() |
![]() |