LoginSignup
1
0

More than 5 years have passed since last update.

ググって調べにくいdefined-or演算子(//)を使ってみる

Posted at

//が出てきてもググれなくて泣かないように確認しておく。

参考

こちらを見て試してみた。

Defined-or演算子「//」 - PerlならサンプルコードPerl入門

第14回 最新Perl使いこなし術―リファレンスの引き方,5.10以降の新機能(2):Perl Hackers Hub|gihyo.jp … 技術評論社

サンプルソース

こんな風にdefine-or演算子はサブルーチンの引数をハッシュやハッシュリファレンスで渡す場合のデフォルト値定義に使える。

a.pl
use v5.10;
use warnings;

test_v5_8();                  # null
test_v5_8(type => "list1");   # hash1
test_v5_8(type => "list2");   # hash2
test_v5_8(+{type => "hash-ref"}); # hash-ref

test_v5_10();                  # null
test_v5_10(type => 0);         # 0
test_v5_10(type => "list1");   # hash1
test_v5_10(type => "list2");   # hash2
test_v5_10(+{type => "hash-ref"}); # hash-ref

sub test_v5_8 {
  my %args = @_ == 1 ? %{$_[0]} : @_;
  my $type = (exists $args{type}) ? $args{type} : "null";
  say "v5.8 $type";
}

sub test_v5_10 {
  my %args = @_ == 1 ? %{$_[0]} : @_;
  my $type = $args{type} // "null";
  say "v5.10 $type";
}

my %args = @_ == 1 ? %{$_[0]} : @_;についてはlib/Furl/HTTP.pm - metacpan.orgから借用させて頂いた。ハッシュとハッシュリファレンスの違いを一行で吸収してしまうスゴイヤツである。

今まではmy $type = (exists $args{type}) ? $args{type} : "null";と二重に書いていたのがmy $type = $args{type} // "null";と一回に収まるがとてもスマートである。

1
0
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
0