Perl defined Function



Description

This function returns true if EXPR has a value other than the undef value, or checks the value of $_ if EXPR is not specified. This can be used with many functions to detect a failure in operation, since they return undef if there was a problem. A simple Boolean test does not differentiate between false, zero, an empty string, or the string .0., which are all equally false.

If EXPR is a function or function reference, then it returns true if the function has been defined. When used with entire arrays and hashes, it will not always produce intuitive results. If a hash element is specified, it returns true if the corresponding value has been defined, but does not determine whether the specified key exists in the hash.

Syntax

Following is the simple syntax for this function −

defined EXPR

defined

Return Value

This function returns 0 if EXPR contains undef and 1 if EXPR contains a valid value or reference.

Example

Following is the example code showing its basic usage −

#!/usr/bin/perl

$var1 = "This is defined";

if( defined($var1) ) {
   print "$var1\n";
}
if( defined($var2) ) {
   print "var2 is also defined\n";
} else {
   print "var2 is not defined\n";
}

When above code is executed, it produces the following result −

This is defined
var2 is not defined
perl_function_references.htm
Advertisements