设为首页 收藏本站
查看: 730|回复: 0

[经验分享] perl中的defined和exists

[复制链接]

尚未签到

发表于 2017-5-18 06:46:57 | 显示全部楼层 |阅读模式
  From: http://hi.baidu.com/wangj998/blog/item/3a8d63e9b5b7c035b90e2d3b.html
  exists
  [iyunv@localhost~]# cat 1.pl
#!/usr/bin/perl -w
use strict;
my $a;
my $b="";
my $c=1;
print "a ok/n" if ( defined $a );
print "b ok/n" if ( defined $b );
print "c ok/n" if ( defined $c );
  my %hash=(
'aa' => 'bejing',
);
  if ( exists $hash{'aa'} )
{
print "aa exists/n";
}
else
{
print "aa not exists/n";
}
  结果:
  [iyunv@localhostr ~]# perl -w 1.pl
b ok
c ok
aa exists
# a 没有赋值过值,所以是undef ,b赋值为空,空也是赋值,c赋值,哈希存在aa值
  defined是用来测试一个变量是否是undef的,也就是说这个变量一定有,只是不知道对这个变量赋过值没有

exists一般是用来测试hash表中是否存在一个变量的

exists判断散列或者数组中某值是否存在,defined判断一个值是不是undef。
存在的也有可能是undef。
  defined 一般用来判断变量是非赋值或文件是否都结尾,exists 判断数组哈希是否存在某个变量
  其他网络参考
defined
Perl functions A-Z|Perl functions by category|The 'perlfunc' manpage

  • defined EXPR  


  • defined  Returns a Boolean value telling whether EXPR has a value other than the undefined value undef. If EXPR is not present, $_will be checked.
      Many operations return undefto indicate failure, end of file, system error, uninitialized variable,and other exceptional conditions. This function allows you to distinguish undeffrom other values. (A simple Boolean test will not distinguish among undef, zero, the empty string, and "0", which are all equally false.) Note that since undefis a valid scalar, its presence doesn't necessarilyindicate an exceptional condition: popreturns undefwhen its argument is an empty array, orwhen the element to return happens to be undef.
      You may also use defined(&func)to check whether subroutine &funchas ever been defined. The return value is unaffected by any forward declarations of &func. Note that a subroutine which is not defined may still be callable: its package may have an AUTOLOADmethod that makes it spring into existence the first time that it is called -- seeperlsub.
      Use of definedon aggregates (hashes and arrays) is deprecated. It used to report whether memory for that aggregate has ever been allocated. This behaviormay disappear in future versions of Perl. You should instead use a simple test for size:

    • if (@an_array) {print"has array elements/n" }
    • if (%a_hash) {print"has hash members/n" }
      When used on a hash element, it tells you whether the value is defined, not whether the key exists in the hash. Use"exists"for the latter purpose.
      Examples:

    • printifdefined$switch{'D'};
    • print"$val/n" whiledefined($val =pop(@ary));
    • die"Can't readlink $sym: $!"
    • unlessdefined($value =readlink$sym);
    • sub foo {defined&$bar ? &$bar(@_) :die"No bar"; }
    • $debugging = 0 unlessdefined$debugging;
      Note: Many folks tend to overuse defined, and then are surprised to discover that the number 0and ""(the zero-length string) are, in fact, defined values. For example, if you say

    • "ab" =~ /a(.*)b/;
      The pattern match succeeds, and $1is defined, despite the fact that it matched "nothing". It didn't really fail to match anything. Rather, it matched something that happened to be zero characters long. This is all very above-board and honest. When a function returns an undefined value, it's an admission that it couldn't give you an honest answer. So you should use definedonly when you're questioning the integrity of what you're trying to do. At other times, a simple comparison to 0or ""is what you want.
      See also"undef","exists","ref".

  
exists
Perl functions A-Z|Perl functions by category|The 'perlfunc' manpage

  • exists EXPR  
      Given an expression_r_r_r that specifies a hash element or array element, returnstrue if the specified element in the hash or array has ever been initialized, even if the corresponding value is undefined.

    • print"Exists/n" ifexists$hash{$key};
    • print"Defined/n" ifdefined$hash{$key};
    • print"True/n" if $hash{$key};
    • print"Exists/n" ifexists$array[$index];
    • print"Defined/n" ifdefined$array[$index];
    • print"True/n" if $array[$index];
      A hash or array element can be true only if it's defined, and defined if it exists, but the reverse doesn't necessarily hold true.
      Given an expression_r_r_r that specifies the name of a subroutine, returns true if the specified subroutine has ever been declared, even if it is undefined. Mentioning a subroutine name for exists or defined does not count as declaring it. Note that a subroutinewhich does not exist may still be callable: its package may have an AUTOLOADmethod that makes it spring into existence the first time that it is called -- seeperlsub.

    • print"Exists/n" ifexists&subroutine;
    • print"Defined/n" ifdefined&subroutine;
      Note that the EXPR can be arbitrarily complicated as long as the final operation is a hash or array key lookup or subroutine name:

    • if (exists$ref->{A}->{B}->{$key}) { }
    • if (exists$hash{A}{B}{$key}) { }
    • if (exists$ref->{A}->{B}->[$ix]) { }
    • if (exists$hash{A}{B}[$ix]) { }
    • if (exists&{$ref->{A}{B}{$key}}) { }
      Although the deepest nested array or hash will not spring into existence just because its existence was tested, any intervening ones will. Thus $ref->{"A"}and $ref->{"A"}->{"B"}will spring into existence due to the existence test for the $key element above. This happens anywhere the arrow operator is used, including even:

    • undef$ref;
    • if (exists$ref->{"Some key"}) { }
    • print$ref; # prints HASH(0x80d3d5c)
      This surprising autovivification in what does not at first--or even second--glance appear to be an lvalue context may be fixed in a future release.
      Use of a subroutine call, rather than a subroutine name, as an argument to exists() is an error.

    • exists⊂ # OK
    • exists&sub(); # Error


运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-378546-1-1.html 上篇帖子: Perl SIG信号处理 下篇帖子: 【转】perl实现socket通信
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表