#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $hashref = { hoge => 100, fuga => 200, piyo => 300, }; print Dumper $hashref;
ã¨ãããã·ã¥åæåæã«keyã¨valueã®çµã¿åãããã¾ã¨ãã¦æå®ãããã¨ãããã¨æãã¾ãã
$ perl hoge.pl $VAR1 = { 'piyo' => 300, 'fuga' => 200, 'hoge' => 100 };
ããã§ãvalueã®é¨åã«ãµãã«ã¼ãã³ãã¡ã½ããããã®è¿ãå¤ãå
¥ããããã«ããã¨ãã«æ³¨æã
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $hashref = { hoge => 100, fuga => foo(), piyo => 300, }; print Dumper $hashref; sub foo { return 200; }
ãããªãåé¡ãªãåãã®ã ãã©ãããã§foo()ãè¤æ°è¦ç´ ãæã¤é åãè¿ãã¨â¦
sub foo { return (200, 250); }
Odd number of elements in anonymous hash at hoge.pl line 6. $VAR1 = { '250' => 'piyo', 'fuga' => 200, 'hoge' => 100, '300' => undef };
ãããªãã¨ã«ãªã£ã¦ãã¾ãã
è¦ã¯ãããã·ã¥ã®åæåã£ã¦ãªã¹ãã渡ãã¦ã(0ããå§ãã¦)å¶æ°çªç®ã®è¦ç´ ãkeyãå¥æ°çªç®ã®è¦ç´ ãvalueã¨ããä»çµã¿ãªã®ã§ãfoo()ãè¿ãè¦ç´ æ°ã«ãã£ã¦åæåæã«ä½¿ããããªã¹ãã®è¦ç´ æ°ãå¤ãã£ã¦ãã¾ãã¨ãããããªããã¨ãããã¨ãããªï¼
ä½ãè¿ããªãå ´åããºã¬ã¦ãã¾ãã
sub foo { return; }
Odd number of elements in anonymous hash at hoge.pl line 6. $VAR1 = { 'fuga' => 'piyo', 'hoge' => 100, '300' => undef };
ãªã®ã§ããã®ãããªåæåãè¡ãã¨ãã«ã¯ãµãã«ã¼ãã³ãã¡ã½ããã®è¿ãå¤ã使ããªãããã«ãããã¨ããå¿
ãï¼ã¤ã®scalarå¤ãåãåãããã«ãããã¨ããªããæ°ãã¤ããæ¹ãè¯ããããããªãã
my $hashref = { hoge => 100, fuga => scalar(foo()), piyo => 300, };
ãã£ã¨ãã¹ããªãã©ã¯ãã£ã¹ããããããªæ°ãããâ¦
ããã©ã«ãå¤ã®è©±
ã¨ããã§ãä¸è¨ã®ä¾ã§foo()ãundefãè¿ãå ´åã¯ããã©ã«ãå¤ãè¨å®ããããã«ãã¨ããå ´å
my $hashref = { hoge => 100, fuga => foo() || 200, piyo => 300, };
ã¨ããã£ã¦ãã¾ãããã ãã©ããã®å ´å
sub foo { return 0; }
sub foo { return "0"; }
sub foo { return ''; }
ã¨ãã®å ´åãfoo()ã®è¿ãå¤ã¯å½ã¨ã¿ãªããããã©ã«ãå¤200ãè¨å®ããã¦ãã¾ãã
ãundef以å¤ã®å ´åã ãããã©ã«ãå¤200ã«ããããã¨ããå ´åã¯
my $val; my $hashref = { hoge => 100, fuga => defined($val = foo()) ? $val : 200, piyo => 300, };
ã¨ãããããªã«ã³ã¸ï¼ perl 5.10以éã ã¨"//" (the definedâor operator)ã使ã£ã¦
my $hashref = { hoge => 100, fuga => foo() // 200, piyo => 300, };
ãåãæå³ã«ãªãã®ããªï¼
"return;"ã¨"return undef;"ã¯èå¥ã§ããï¼
å¥ã«valueå¤ã«undefãè¨å®ãã¦ãããã®ã ãã©ãfoo()ã®è¿ãå¤ãç¡ãå ´å(ä½ãè¿ããªãreturnã®å ´å)ã ãããã©ã«ãå¤ã«ããããã¨ãããã¨ã¯åºæ¥ãã®ã ãããï¼
ã¤ã¾ãä¸è¨ã®ãã¹ããéãããã«ããããã¨ããå ´åï¼
#!/usr/bin/perl use strict; use warnings; use Test::More tests => 5; sub hoge { my $code = shift; return $code->() // 200; } is(hoge(sub { return 0; }), 0 ); is(hoge(sub { return ''; }), '' ); is(hoge(sub { return '0'; }), '0'); ok(! defined(hoge(sub { return undef; }))); is(hoge(sub { return; }), 200);
ãã®å ´åã ã¨4çªç®ãhoge(undef)ã®è¿ãå¤ãundefãããªããªãããNGã
sub hoge { my $code = shift; my @a; return scalar(@a = $code->()) ? $a[0] : 200; }
ããããã°ä¸å¿éããã©ããã¢ãã
"return;"ã¨"return undef;"ãåºå¥ããããªãã¦ããå ´åã¯ããããç¡ãã¨æããã©ãã©ãããã°è¯ãã®ãã¯æ°ã«ãªãããã