LoginSignup
1
1

More than 5 years have passed since last update.

Perl:サブルーチンをOptionalみたいに異なる引数で呼びたい

Posted at

(問)
1、2、3を渡すと6が返ってくる
1、2を渡すと3が返ってくる

hoge.pl
use strict;
use warnings;
use utf8;
use 5.014;

my $result;

# 引数3つ
$result = hoge(1, 2, 3);
print $result, "\n"; # result = 6

# 引数2つ
$result = hoge(1, 2);
print $result, "\n"; # result = 3

sub hoge {
    my ($a, $b, $c) = @_;

    my $result = 0;
    $result += $a if defined $a;
    $result += $b if defined $b;
    $result += $c if defined $c;

    return $result;
}

1;

@_ は受け取った引数を順番に格納していく
引数を無作為にしたい場合や変数名を指定したい場合は使えない

Maybeを使った方法もある

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1