Home > Articles > Web Development > Perl

  • Print
  • + Share This
From the author of

Scalar Quickie

This is a fast example of a class that will tie() a scalar variable to a text file. This is different from the earlier example in the "Constructors/Destructors" section of a string value living in a text file being assigned to the tying scalar. In this case, the text file keeps a log of all the times the scalar variable is changed or its value is FETCHED. Take what you've learned about tying with hashes and apply it to the module below:

# Usage: tie($VARIABLE,'TrackScalar', FILE, "\$VARIABLE name/description");


# use TrackScalar;
# my $var;
# tie($var, 'TrackScalar', 'track.txt', "\$var (keeps count)");

package TrackScalar;

use strict;
use vars qw($VERSION @ISA);

# Get Revision number from RCS
($VERSION = substr(q$Revision: 0.2 $, 10)) =~ s/\s+$//;

sub Version {return $VERSION;}

use IO::File;

# Create tied scalar

sub TIESCALAR {
    my $class = shift;
    my $log = shift;
    my $var = shift || "(undefined)";
    my $fh = new IO::File ">> $log" or die "Cannot open $log: $!\n";


    # Notice that the variable being blessed in the object is an 
    # anonymous hash, and this is tied to the scalar
    return bless {FH => $fh, VAL => 0, VAR => $var}, $class;
}

sub FETCH {
    my $self = shift;
    my ($package, $filename, $line) = caller();
    my $fh = $self->{FH};
    print $fh "package $package, $filename line $line FETCHED $self->{VAR}\n";

    return $self->{VAL};
}

sub STORE {
    my $self = shift;
    my $var = shift;
    my $fh = $self->{FH};
    my ($package, $filename, $line) = caller();
    print $fh "package $package, $filename line $line changed $self->{VAR} to $var\n";
    $self->{VAL} = $var;
}

sub DESTROY {
    undef ${$_[0]};
}

1;
  • + Share This
  • 🔖 Save To Your Account