Perl defined Function

These sites are FOR SALE: miscperlinfo.com, mpihowto.com!
If you are interested, please use my Contact page.




Perl defined function allows you to check whether a function or a variable is defined or not. This short free tutorial will show you some interesting ways to use it in your Perl scripts.

To begin with, this built-in Perl function has two syntax forms:

defined EXPR
defined

and returns false whether EXPR has the value undef and true otherwise. If EXPR is omitted (as in the second syntax form), the special variable $_ will be tested.


Click Below to See the Best

Perl How-to Snippet Collection

and Save Hours of Surfing on Internet!


I remind you that undef (undefined value) is a special datatype valid scalar that performs a similar role as NULL does in C language. By instance, a scalar value can be either defined (in this case can be a string, a number or a reference) or undefined (the undef value). The undef can be used as a function too, in order to make undefined the value of a certain variable.

Anytime we declare a variable in Perl without initializing it, automatically it will take the undef value. So we use the defined function to check-up if a variable is defined (it was assigned some value to it) or has the undef value.

Please note that you can’t use the boolean conditions to verify if a value is defined, for the simple reason that undef, 0, the empty string ("") and "0" are evaluated as false in Perl.

In the following, we will show you a few examples about how to use the Perl defined function with scalars, arrays, hashes or subroutines.

How to use Perl defined function with scalars


As I mentioned before, if you declare a scalar variable and do not assign any value to it, that variable will have the undef value. If you’ll run the script with the -w flag warning turned on like in the next two lines example:

#!/usr/bin/perl –w

print $v;

you’ll get a warning message on STDERR and as output nothing because Perl will treat the undef value of the $v variable as either 0 or the empty string.

You can use the ternary conditional operator ? to check-up if a scalar variable is defined or not. See the next short snippet code for this:

my $v1;
my $v2 = 1;

defined($v1) ? print "v1 defined\n" : print "v1 not defined\n";
defined($v2) ? print "v2 defined\n" : print "v2 not defined\n";

undef $v2;
defined($v2) ? print "v2 defined\n" : print "v2 not defined\n";

This code will produce as output:

v1 not defined
v2 defined
v2 not defined

As you can see in this example, after we initialize the $v2 scalar variable with 1, we can set it undefined again by using undef as either a function or a value.

How to use Perl defined function with an array


For an array the Perl defined function is deprecated and we can better use defined for the elements of the array. However, if you declare an array without assigning it any element, if you call the defined function against the array, the undef value will be returned:

my @array;
print "not defined\n" unless defined(@array); 
# displays: not defined
@array = qw(1 2 3 4);
print "defined\n" if defined(@array); 
# displays: defined
# now we clear the array
@array = ();
print "defined\n" if defined(@array); 
# displays: defined
undef @array;
print "not defined\n" unless defined(@array); 
# displays: not defined

As you can see from the above example, for arrays the Perl defined function reports only whether the array has been ever allocated; if we assign to it an empty list and call again the defined function, this time it will return true (because the array was allocated before). If we declare our array with undef, the defined function will return undef (but not like @array = undef because in this case the array has one element – the undef scalar value).

Therefore, be aware any times you are tented to call the defined function against an entire array. The next examples will show you how to use the defined function with the elements of an array.

# initializing an array
my @array = qw(zero one two three four);
$array[7] = "seven";
$array[9] = "nine";
for(my $i=0; $i<=20; $i++) {
  print $array[$i]," " if defined($array[$i]);
}
print "\n";
# it displays: zero one two three four seven nine

The above program assigns values to the elements of the array with the subscripts : 0, 1, 2, 3, 4, 7, 9 respectively. The for loop will print the elements of the array for which the defined function returns true.


How to use Perl defined function with a hash


Using the Perl defined function with an entire hash is deprecated and should be avoided (see the above considerations for arrays). Instead, you can use it with the hash pair elements, this function will not report if a key exists but if the corresponding value of the key is defined.

The following example will print only the keys of a hash that have defined corresponding values:

# initialize a hash aggregate
my %numbers = (zero => 0, one => 1, two => undef,  three => 3);
# now we print the keys for which the values are defined
foreach my $key (keys %numbers) {
  print "$key "  if defined($numbers{$key});
}
print "\n";
# it displays: three one zero

The next code could be used in a more general context and allows you to increase an array of words with new words, by eliminating duplicates. The new words could be read line by line from and afterwards appended to our array.

We will take here a more simple example. Let’s say that we have the @colors array with some colors as elements and we want to enlarge this array with new colors by printing and eliminating duplicates.

At the @colors array we will associate the %colors hash that has ($color, 1) as pair element where $color represents an element of the @colors array and 1 has the significance that $color belongs to @colors array.

Anytime we’ll find a new color to append to our @colors array, we will update the %colors hash too by adding the ($color, 1) pair element to it. To check if the $color exists already, we use the Perl defined function.

Please note that @colors and %colors are distinct structures, and Perl knows to make the difference between them.

Here is the code:

# initialize the @colors array
my @colors = qw(white blue red);
my %colors;

# setting the corresponding hash structure
foreach my $color (@colors) {
  $colors{$color} = 1;
}

# initialize the @newcolors structure
my @newcolors = qw(grey green white yellow red cyan);

foreach my $color (@newcolors) {
  if(defined($colors{$color})) { 
    print "duplicate color: $color\n";  
  } 
  else { $colors{$color} = 1; push(@colors, $color); }
}
# display the @colors array
print "@colors\n";

The output for this code will be:

duplicate color: white
duplicate color: red
white blue red grey green yellow cyan

How to use Perl defined function with


You can use the Perl defined function to test if the line-input operator reached the end of file. Generally, this operator returns a line of text, but if there are not more input lines, it returns the undef value. It is very useful when you want to distinguish between an empty line and the end of file.

See the following code snippet for an example:

while(defined(my $input = )) {
  chomp $input;
  print "input line: $input\n";
}

The while loop will end when will return undef, i.e. the end of file will be reached (either we read from a file or from the keyboard). The chomp
function is used to get rid of the eventually trailing newline.

If you want to download the Perl defined script with all the above examples included, please click here: Script download

A-N-Y-O-N-E Can Learn and Master Perl!
And That Includes YOU!


Check these how-to tutorial eBooks (PDF format):


Table of Contents:

A Perl Script
Install Perl
Running Perl
Perl Data Types
Perl Variables
Perl Operators
Perl Lists
Perl Arrays
    Array Size
    Array Length
Perl Hashes
Perl Statements
    Perl if
    Perl unless
    Perl switch
    Perl while
    Perl do-while
    Perl until
    Perl do-until
    Perl for
    Perl foreach
Built-in Perl Functions
    Functions by Category
        String Functions
        Regular Expressions and Pattern Matching
        List Functions
        Array Functions
        Hash Functions
        Miscellaneous Functions
    Functions in alphabetical order
        chomp
        chop
        chr
        crypt
        defined (more)
        delete
        each
        exists
        grep
        hex
        index
        join
        keys
        lc
        lcfirst
        length
        map
        oct
        ord
        pack
        pop
        push
        q
        qq
        qw
        reverse
        rindex
        scalar
        shift
        sort
        splice
        split
        sprintf
        substr
        tr
        uc
        ucfirst
        undef
        unpack
        unshift
        values

return from Perl defined Function to Perl Basics



Would you like to create your own website like this one?
Hit the Alarm Clock!

Site Build It!