Mooseを試そう
30分プログラム、その509。Perlのモダンなオブジェクトシステム、Mooseを試してみた。
銀行口座クラスをとりあえず作ってみたけど、これだけだとあまり利点が感じられない。せいぜいアトリビュートを簡単に定義できるぜい、という程度。
きっとbefore/after/aroundとかのMOP周りの機能を使うと、Moose SUGEEE!!みたいになるんだろうなぁ。
使い方
use Data::Dumper; my $account = Account->new(balance=>420); $account->deposite(100); $account->withdraw(50); print Dumper($account);
ソースコード
#! /usr/bin/perl # -*- mode:perl; coding:utf-8 -*- # # moose-test.pl - # # Copyright(C) 2009 by mzp # Author: MIZUNO Hiroki / mzpppp at gmail dot com # http://howdyworld.org # # Timestamp: 2009/01/18 22:40:06 # # This program is free software; you can redistribute it and/or # modify it under MIT Lincence. # use strict; use warnings; package Account; use Moose; has 'balance',is=>'rw',isa=>'Int',default=>0; sub withdraw{ my ($self,$n) = @_; if($self->balance > $n){ $self->balance($self->balance - $n); }else{ 'error'; } } sub deposite{ my ($self,$n) = @_; $self->balance($self->balance + $n); } package main; use Data::Dumper; my $account = Account->new(balance=>420); $account->deposite(100); $account->withdraw(50); print Dumper($account);