デフォルト値のperlらしい指定法

| 0 Comments | 0 TrackBacks | このエントリーをはてなブックマークに追加 このエントリーのはてなブックマーク件数

のダイジェスト。

Scalarによるデフォルト値

sub num{
    my $num = shift || -1; 
    # ....
}

0や''を入力値として用いたい場合は

sub num{
    my $num = shift;
    $num = -1 if not defined $num;
    # ....
}

Perl 5.10.0 以降なら

sub num{
    my $num = shift // -1;
    # ....
}

Hashによるデフォルト値

以下で一発!

sub conf{
    my %arg = (
        lang => 'perl',
        rank => 1,
        @_ # ここが決め手!           
    );
    # ...
}

オブジェクトをnewしたいなら、以下がお手軽。

package A::Module
sub new{
    my $pkg = shift;
    bless {
        lang => 'perl',
        rank => 1,
        @_
    }, ref $pkg || $pkg;
}

Dan the Perl Monger

No TrackBacks

TrackBack URL: http://perl-mongers.org/MT/mt-tb.cgi/66

Leave a comment

About this Entry

This page contains a single entry by dankogai [livedoor.com] published on July 2, 2008 11:17 PM.

実用! PerlでコマンドラインからTwitter投稿 was the previous entry in this blog.

実用! 画像でブックマーク数を返すSBMからブックマーク数を数値で取得 is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Categories

Pages

Creative Commons License
This blog is licensed under a Creative Commons License.
Powered by Movable Type 4.21-en