Home > Articles > Web Development > Perl

  • Print
  • + Share This
From the author of

Constructors/Destructors

When a variable is tied to a class, the TIE* constructor is called.

The constructor can do almost whatever the programmer wants it to. It may simply check to see if the resource to be tied to exists. It could create it if it doesn't exist, or load the resource into memory; or it could add an internal pointer to the resource in the class as object data. For example, if it's a directory to be tied to, the constructor may check to see if that directory exists, and if it does, it will save the location of that directory to the class object.

Following is how Tie::Dir's TIEHASH constructor results in a tie() of a variable (in this case, %hash) to the current directory (.), and whether or not deleting is allowed:

# tie %hash, Tie::Dir, ".", DIR_UNLINK;

sub TIEHASH {
    my($class,$dir,$unlink) = @_;
    $unlink ||= 0;
    bless [$dir,undef,$unlink], $class;
}

One use of tying is for keeping a certain variable persistent through web-based sessions. For example, suppose people log into your web site via basic authentication, and a file is saved that contains the city they live in, based from input from a web-based form. That information is then used to create dynamic pages when they return to the site, almost like a server-side cookie. Now suppose I'm the user, my username is kmeltz, and I'm from Fooville. You may have a file named kmeltz.city with the contents being a string, Fooville. You could tie() to this scalar (the string Fooville) with a constructor like this:

sub TIESCALAR {
    my $class = shift;
    my $name = shift;
    my $city = system("/bin/cat", "$name\.city");

    return bless \$city, $class;
}

In the calling script, you would get the information like this:

use Tie::getCity; # If the module name was Tie/getCity.pm

tie($foo, 'Tie::getCity', $ENV{REMOTE_USER});

Now $foo's value is the string Fooville, and this information can be used to create dynamic content across your web site.

When the variable is untied (described later), goes out of scope, or the program ends, the object associated with the variable is destroyed. The regular object destructor method DESTROY is called. It's a very good habit to untie() tied variables when they're no longer needed. You would untie() $foo from the above example like this:

untie $foo;
  • + Share This
  • 🔖 Save To Your Account