Null object: Difference between revisions

Content added Content deleted
m (→‎[[Undefined values#ALGOL 68]]: add "works with", fixed gramma and formatting.)
Line 408:
 
=={{header|Perl}}==
In Perl, <code>undef</code> is a special scalar value, kind of like null in other languages. A scalar variable that has been declared but has not been assigned a value will be initialized to <code>undef</code>. (Array and hash variables are initialized to empty arrays or hashes.)
In Perl, all variables are undefined by default. The <tt>defined</tt> function returns true iff its argument is defined. Hence, this statement on its own will print "Undefined."
 
<lang perl>print +(defined $x ? 'Defined' : 'Undefined'), ".\n";</lang>
If <code>strict</code> mode is not on, you may start using a variable without declaring it; it will "spring" into existence, with value <code>undef</code>. In <code>strict</code> mode, you must declare a variable before using it. Indexing an array or hash with an index or key that does not exist, will return <code>undef</code> (however, this is not an indication that the index or key does not exist; rather, it could be that it does exist, and the value is <code>undef</code> itself). If <code>warnings</code> is on, most of the time, if you use the <code>undef</code> value in a calculation, it will produce a warning. <code>undef</code> is considered false in boolean contexts.
 
It is possible to use <code>undef</code> like most other scalar values: you can assign it to a variable (either by doing <code>$var = undef;</code> or <code>undef($var);</code>), return it from a function, assign it to an array element, assign it to a hash element, etc. When you do list assignment (i.e. assign a list to a list of variables on the left side), you can use <code>undef</code> to "skip" over some elements of the list that you don't want to keep.
 
You can check to see if a value is <code>undef</code> by using the <code>defined</code> operator:
<lang perl>print +defined(defined $x) ? 'Defined' : 'Undefined'), ".\n";</lang>
From the above discussion, it should be clear that if <code>defined</code> returns false, it does not mean that the variable has not been set; rather, it could be that it was explicitly set to <code>undef</code>.
 
Starting in Perl 5.10, there is also a [http://perldoc.perl.org/perlop.html#C-style-Logical-Defined-Or defined-or] operator in Perl. For example: