Wednesday, August 6, 2008

Deleting Variables

is in order. Suppose we want to delete Hamburg from the following array. How do we do it ? Perhaps:
@cities=("Brussels","Hamburg","London","Breda");

&look;

$cities[1]="";

&look;

sub look {
print "Cities: ",scalar(@cities), ": @cities\n";
}

would be appropriate. Certainly Hamburg is removed. Shame, such a great lake. But note, the array element still exists. There are still four elements in @cities. So what we need is the appropriate splice function, which removes the element entirely.

splice (@cities, 1, 1);

Now that's all well and good for arrays. What about ordinary variables, such as these:

$car ="Porsche 911";
$aircraft="G-BBNX";

&look;

$car="";

&look;

sub look {
print "Car :$car: Aircraft:$aircraft:\n";
print "Aircraft exists !\n" if $aircraft;
print "Car exists !\n" if $car;
}

It looks like we have deleted the $car variable. Pity. But think about it. It is not deleted, it is just set to the null string "". As you recall (hopefully) from previous ramblings, the null string evaluates to false so the if test fails.


False values versus Existence: It is, therefore...
Just because something is false doesn't mean to say it doesn't exist. A wig is false hair, but a wig exists. Your variable is still there. Perl does have a function to test if something exists. Existence, in Perl terms, means defined. So:

print "Car is defined !\n" if defined $car;

will evaluate to true, as the $car variable does in fact exist.

This begs the question of how to really wipe variables from the face of the earth, or at least your Perl script. Simple.

$car ="Porsche 911";
$aircraft="G-BBNX";

&look;

undef $car; # this undefines $car

&look;

sub look {
print "Car :$car: Aircraft:$aircraft:\n";
print "Aircraft exists !\n" if $aircraft;
print "Car exists !\n" if defined $car;
}

This variable $car is eradicated, deleted, killed, destroyed.

And now for something completely different....

No comments: