Home
FREE Newsletter
Perl How To
Perl Books
Perl Basics
Perl Editors
Perl Modules
Perl Database
Net Programming
Sitemap
About Me
Contact Me
Blog
 

Perl defined Function



NEW!!!

Check my new resource:    Perl How To Tutorial eBooks



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.


Check my new How To Tutorial eBooks (PDF format):

to see a lot of fully commented examples that help you use the Perl statements and the Perl built-in functions in your scripts.


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 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 we declare an array without assigning it any element, if we 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.


Check my new How To Tutorial eBooks (PDF format):

to see a lot of fully commented examples that help you use the Perl statements and the Perl built-in functions in your scripts.



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 <STDIN> 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 element pairs 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 pair ($color, 1) element to it. To check if the $color exists already, we use the 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 <STDIN>


You can use Perl defined function to test if the line-input operator <STDIN> 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 snippet code for an example:

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

The loop while will end when <STDIN> 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



Subscribe now to my FREE newsletter
(regarding tips and tricks to manipulate multidimensional
arrays and hashes in Perl)

and you'll receive a link to download for FREE my Perl chomp Function Tutorial eBook, it's a bonus for you and I hope you'll enjoy it. You can see its Table of Contents here (if you subscribe to my free newsletter, you don't have to pay for this eBook or use your paypal account).


Don't forget to check my new How To Tutorial eBooks (PDF format):

to see a lot of fully commented examples that help you use the Perl statements and the Perl built-in functions in your scripts.






NEW!!!

Do you want more information about the basic Perl topics?

Check my new "Perl How To" Tutorial eBooks page where I'll answer the most frequent questions regarding some topics :


Perl How To Tutorial eBooks


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
        List Functions
        Array Functions
        Hash Functions
        Miscellaneous Functions
    Functions in alphabetical order
        chomp
        chop
        chr
        crypt
        defined
        delete
        grep
        hex
        index
        join
        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
        unshift

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!


footer for perl defined page