Perl undef Function



Perl undef function returns an undefined value, freeing up the memory used by the variable arguments passed to it. You can use this function with scalars, lists or arrays, hashes, functions or typeglobs. In this short free tutorial I’ll show you some opportunities about using this built-in function in your Perl scripts.


Click Below to See the Best

Perl How-to Snippet Collection

and Save Hours of Surfing on Internet!


For this function two syntax forms are available, as shown below:

undef EXPR
undef

When you declare for first time a variable in Perl without assigning any value to it, Perl will assign by default the undef value to it. If you forget to assign any value to a variable declared in a Perl script, there are chances that your script will not crash if you will run it.

But if you’ll use warnings, Perl will always warn you if you have unassigned variables in your script. It’s a good habit to use warnings because all your typos will have the undef value assigned and Perl will warn you about them.

You can omit the expression when you use undef and in this case undef is a lvalue, the undefined value being a special data type, a special case of a scalar value. If you’ll use it without EXPR, the Perl undef function will return the undefined value.

For numeric scalar variables the undef value is 0, meanwhile for string variables it indicates an empty string. To distinguish between 0 / empty strings and the undef value, Perl provides the defined function that allows you to check up if a variable has the undef value or not.

Next, I’ll show you some ways to use this function.


How to use Perl undef function with scalars


See the following snippet code:

# declare a scalar variable without initializing it
my $var1;
# declare a scalar variable and assign a value to it
my $var2 = "Perl undef function";
print "var1 undefined\n" unless defined $var1;
print "var2 defined\n" if defined $var2;

# free resource for $var2 and make it undefined
undef $var2;
print "var2 undefined\n" unless defined $var2;

and the output for this code:

var1 undefined
var2 defined
var2 undefined

How to use Perl undef function with arrays


If you want to free up the memory resources occupied by a big array, you can use the undef function like in the following lines of code:

my @array = <STDIN>;
# perform some actions with the array’s elements
# …

# free the memory where the array was stored
undef (@array);
print "\@array is undefined\n" unless defined(@array);

In the above code, we read from standard input some lines of data and we store them in the @array. After performing some tasks against the elements of the array, we free up the memory usage by that array variable. If you execute this code, finally the message: "@array is undefined" will be printed. However, please note that if you have a multidimensional array, which has some references to other structures, it is not enough to free the initial array only. To illustrate, please see the next code:

# declare and initialize some arrays
my @array1 = qw(1 2 3 4);
my @array2 = qw(5 6 7 8);
# define a reference for the second array
my $ref2 = \@array2;
# append the reference o the first array
push @array1, $ref2;

# free the memory usage by @array1;
undef (@array1);
print "\@array2 still available: @array2\n";
# it displays: @array2 still available: 5 6 7 8

If you want to free the usage memory for an array and for all its references too, you must consider to step down in a recursive way through all the array references and free the usage memory until no more references are found. To see if an element of an array is a reference to some other data type structure, you can use the ref function, something like in the next lines of code:

use warnings;

my @array1 = qw(1 2);
my @array2 = qw(3 4);
$array1[2] = \@array2;

for(my $i=0; $i<scalar (@array1); $i++)
{
  if(ref $array1[$i] eq "") {
    print "$i: NO REFERENCE\n";
  } elsif (ref $array1[$i] eq "ARRAY") {
    print "$i: ARRAY\n";
  }
}

and the output:

0: NO REFERENCE
1: NO REFERENCE
2: ARRAY

You can use undef against certain elements of an array:

use warnings;

my @array = qw(1 2 3);
undef $array[1];
print "array size = ",scalar @array, "\n";
# displays: array size = 3

The second element of the array will have the undef value, but the dimension of the array doesn’t change.


How to use Perl undef function with hashes


The below code will show you how to use Perl undef upon an entire hash (free up the memory usage by it) or to undef certain elements of the hash. If you want to delete an entry from a hash, you must use the delete function instead. Using Perl undef with a $key element of a hash (using either undef $hash{$key} or $hash{$key} = undef) will only have as effect to undefine the respective value associated with the $key. The following code speaks by itself:

#define a hash and assign some elements to it
my %hash = (1 => "one",   2 => "two", 
         3 => "three", 4 => "four");

# undef the value of the elemnt with the key 2
undef $hash{2};

# undef the value of the elemnt with the key 3
$hash{3} = undef;

# delete the element with the value 4
delete $hash{4};

#undef the entire hash
undef %hash;

How to use Perl undef function with subroutines


There are cases when you want to write a subroutine that returns an undef value if some errors happen. The next example will show you how to return undef if you divide some numbers by 0.

sub divSub {
  local ($n, $k) = @_;
    return ($k == 0 ? undef : $n / $k);
}

($n, $k) = (25, 0);
# divide $n by $k
print  "Can\'t divide by 0\n" unless defined divSub($n, $k);
# it displays: Can't divide by 0

Please click here to download the Perl undef script with all the above examples included.

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
        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 (more)
        unpack
        unshift
        values

return from Perl undef Function to Perl Basics



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

Site Build It!