definedé¢æ° - å¤ãå®ç¾©ããã¦ãããã確èªãã
ãå¤ãå®ç¾©ããã¦ãããã確èªããã«ã¯definedé¢æ°ã使ç¨ãã¾ãã
# å¤ãå®ç¾©ããã¦ãããã®ç¢ºèª $is_defined = defined $value;
å®ç¾©ããã¦ããã¨ã¯
definedé¢æ°ã§å¤å®ã§ããå®ç¾©ããã¦ããå¤ã¨ã¯ãªãã§ãããããèãã¦ã¿ã¾ãããã
å¤æ°å®£è¨ããå ´åã¯ãä»£å ¥ã«ããåæåãè¡ããªãã£ãå ´åã¯æªå®ç¾©ã¨ãªãã¾ãã
# 宣è¨ç´å¾ã¯æªå®ç¾© my $value;
å¤ãä»£å ¥ããã¨ãå¤ãå®ç¾©ããã¦ããç¶æ ã«ãªãã¾ãã
# å¤ãä»£å ¥ããã®ã§å®ç¾©ããã¦ããç¶æ ã«ãªã $value = 5;
undef関数ã使ã£ã¦ãæªå®ç¾©å¤ãä»£å ¥ãããã¨å¤ã¯æªå®ç¾©ã«ãªãã¾ãã
# undefãä»£å ¥ããã¨æªå®ç¾©ã«ãªã $value = undef;
çå½å¤ã¨ã®éãã¯?
definedé¢æ°ã§å¤å®ã§ãããå®ç¾©ããã¦ãã/å®ç¾©ããã¦ããªããã¨ããã®ã¯ãç/å½ãã¨ããæ¦å¿µã¨ã¯ç°ãªããã¨ã«æ³¨æãã¦ãã ãããå®ç¾©ããã¦ããã¨ã¯æªå®ç¾©å¤ã§ã¯ãªãã¨ãããã¨ã§ãã
ä¸æ¹ãçã§ããã¨ããã®ã¯Perlã«ãããå½ã®å¤ã§ã¯ãªãã¨ãããã¨ã§ããçå½å¤ã«ã¤ãã¦ã¯ä»¥ä¸ã®è¨äºãåèã«ãã¦ãã ããã
ãããã·ã¥ã®å¤ãå®ç¾©ããã¦ãããã¨ããã¼ãåå¨ãã¦ãããã®ã¨ã®éãã¯?
exists関数ã使ãã¨ããã·ã¥ã®ãã¼ãåå¨ãã¦ãããã©ããã確èªãããã¨ãã§ãã¾ãããã¼ãåå¨ãã¦ãããã¨ã¨ãå¤ãå®ç¾©ããã¦ãããã¨ã¯ç°ãªããã¨ã§ãã
definedé¢æ°ã«ããå¤å®ã¨existsé¢æ°ã«ããå¤å®ã®çµæã¯ç°ãªããã¨ãããã¾ãã
次ã®ãããªå ´åã¯ãå¤ã¯æªå®ç¾©ã ããã©ãããã·ã¥ã®ãã¼ã¯åå¨ãã¦ããã¨ããã¾ãã
my %scores; # ãã¼ã¯åå¨ããããå¤ã¯æªå®ç¾© $scores{math} = undef;
é åã¨ããã·ã¥ã¸ã®defineé¢æ°ã¯å»æ¢äºå®
é åã¨ããã·ã¥ã¯å®£è¨ãããã¨æªå®ç¾©å¤ã«ã¯ãªããã«ã空ãªã¹ããä»£å ¥ããã¾ãã
my @nums; my %scores;
ããã¯ä»¥ä¸ã¨åãã§ãã
my @nums = (); my %scores = ();
é åãããã·ã¥ã«å¯¾ããdefinedé¢æ°ã«ä½¿ç¨ã¯å»æ¢äºå®ã¨ãªã£ã¦ãã¾ãã代ããã«åç´ã«ç©ºãªã¹ãã§ãããã©ããããã§ãã¯ãã¦ãã ããã
if (@nums) { ... } if (%scores) { ... }
便å©ãªDefined-oræ¼ç®å
å¤ãæªå®ç¾©ã ã£ãå ´åã«å³è¾ºãä»£å ¥ã§ããDefined-or演算子ã¨ãã便å©ãªæ¼ç®åãããã®ã§ç´¹ä»ãã¦ããã¾ãã
my $num; # æªå®ç¾©ã ã£ãããdefined-oræ¼ç®ãã使ã£ã¦3ãä»£å ¥ $num //= 3;
ãµã³ãã«
definedé¢æ°ã使ã£ã¦å®ç¾©ããã¦ãããã©ããã確èªãããµã³ãã«ã§ãã
use strict; use warnings; my $num = 3; if (defined $num) { print "Defined\n"; } else { print "Not defined\n"; }
å®ç¾©ããã¦ããªããã¨ã主è¦ãªãã¸ãã¯ã§ãã£ãå ´åã¯unlessã¨çµã¿åãããã®ãèªã¿ãããã§ãã
use strict; use warnings; my $num; unless (defined $num) { print "Not defined\n"; }