Last active
February 24, 2017 05:54
-
-
Save karupanerura/7e866102bb6f9238f103 to your computer and use it in GitHub Desktop.
Perlのサブルーチンにおいて引数を解釈するということ
This file contains 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
use strict; | |
use warnings; | |
use utf8; | |
use feature qw/say/; | |
# add3(1, 2, 3) => 6 | |
# Perlの引数は@_という配列に入るのでそれに名前を付けるために変数に代入 | |
sub add3 { | |
my ($left, $middle, $right) = @_; | |
return $left + $middle + $right; | |
} | |
say "add3(1, 2, 3) => ", add3(1, 2, 3); | |
# add2(1, 2) => 3 | |
# shiftは引数を省略するとshift @_という意味になる | |
sub add2 { | |
my $left = shift; # => 1 | |
my $right = shift; # => 2 | |
return $left + $right; | |
} | |
say "add2(1, 2) => ", add2(1, 2); | |
# addx(1, 2, 3, 4, ...) | |
# @_は配列なので、引数がいくつだとしても処理できる(可変長引数) | |
sub addx { | |
my $result = 0; | |
for my $num (@_) { | |
$result += $num; | |
} | |
return $result; | |
} | |
say "addx(1, 2, 3, 4, 5, 6, 7, 8, 9) => ", addx(1 .. 9); | |
# add3x(1, 2, 3) => 4 | |
# shiftは配列から先頭を一つ取り除くので、引数の先頭を1つだけ利用してあとは他のサブルーチンでそのまま利用することもできる | |
sub add3x { | |
my $right = shift; | |
return $right + add2(@_); | |
} | |
say "add3x(1, 2, 3) => ", add3x(1, 2, 3); | |
# addxr(1, 2, 3, 4, ...) | |
# shiftは配列から先頭を一つ取り除くので、再帰にも利用できる | |
sub addxr { | |
return shift(@_) if @_ == 1; | |
return shift(@_) + addxr(@_); | |
} | |
say "addxr(1, 2, 3, 4, 5, 6, 7, 8, 9) => ", addxr(1 .. 9); |
This file contains 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
use strict; | |
use warnings; | |
use utf8; | |
use feature qw/say/; | |
# @_は引数そのものなので、@_に代入すると引数自体を書き換える | |
# 引数に変数が与えられた場合、その内容を書き換えることになる | |
sub swap { | |
my $temp = $_[0]; | |
$_[0] = $_[1]; | |
$_[1] = $temp; | |
} | |
my ($a, $b) = ('a', 'b'); | |
say "[BEFORE]"; | |
say "a: $a"; | |
say "b: $b"; | |
swap($a, $b); | |
say "[AFTER]"; | |
say "a: $a"; | |
say "b: $b"; |
This file contains 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
use strict; | |
use warnings; | |
use utf8; | |
use feature qw/say/; | |
# @_は引数を示す配列である。配列をスカラーコンテキストで評価すると配列のサイズを示す。 | |
# 引数を単純にスカラー変数に代入しようとすると、スカラーコンテキストで配列を評価した値が代入される。 | |
# この仕様が組み合わさり、このケースでは直感に反して配列のサイズが代入される。(コンテキストをよく理解していればこの挙動は自明だが、最初はハマりやすい。) | |
sub identity { | |
my $num = @_; | |
return $num; | |
} | |
say "identity('foo') => ", identity('foo'); # => 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment