Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of double negation (!!) [duplicate]

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?

like image 357
Chankey Pathak Avatar asked Sep 05 '12 10:09

Chankey Pathak


1 Answers

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.
like image 77
ronalchn Avatar answered Oct 11 '22 22:10

ronalchn