Use of double negation (!!) [duplicate]

天涯浪子 提交于 2020-01-30 04:05:28

问题


Okay so I came across a code which looks like

@documents_names = sort {
         !!$deleted_documents_names{$a} == !!$deleted_documents_names{$b}
          ? uc($a) cmp uc($b)
          : !!$deleted_documents_names{$a}
          cmp !!$deleted_documents_names{$b}
         } @documents_names;

It's the first time I'm seeing the use of double negation. What's the use of it? When would a person use it?


回答1:


It converts non-boolean types to boolean (dualvar(0,"") or 1).

It is a shortcut way of doing this, instead of trying to cast it explicitly (which may take more characters). The ! operator negates the truthness of its argument. Hence, two of them are used.

Many object types are "truthy", and others are "falsey".

  • The only false values are 0, undef, "", "0" and some overloaded objects.
  • Examples of true values are 1, "asdf", and all other values.



回答2:


That is a lot of funk for a sort block!

It's essentially a two-level sort :

  1. ascii-betical
  2. deleted files first, then undeleted

So one could rewrite it as (untested):

@documents = sort {  exists $deleted_documents_names{$a} # same effect as '!!'
                       <=> 
                     exists $deleted_documents_names{$b}
                  ||
                     uc( $a ) cmp uc( $b )
                  }
             @documents;


来源:https://stackoverflow.com/questions/12278997/use-of-double-negation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!