For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > July 2004 > Keeping track of a variable









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Keeping track of a variable
Alok Bhatt

2004-07-29, 3:55 am

Hi All,

Can someone please tell me how do we keep track of a
variable. ie Whenever a particular variable is
accessed (printed, incremented .... etc.), a counter
should increase, so that we can know how many times it
has been accesssed.

Thanks in Advance,
Regards,
Alok



__________________________________
Do you Yahoo!?
Yahoo! Mail - 50x more storage than other providers!
http://promotions.yahoo.com/new_mail
Randy W. Sims

2004-07-29, 8:55 am

Alok Bhatt wrote:
> Hi All,
>
> Can someone please tell me how do we keep track of a
> variable. ie Whenever a particular variable is
> accessed (printed, incremented .... etc.), a counter
> should increase, so that we can know how many times it
> has been accesssed.


The mechanism is tie, see `perldoc tie`

Here is an example: (See CPAN for others)

#!/usr/bin/perl

package Traced::Var;

use strict;

require Tie::Scalar;

our @ISA = qw(Tie::StdScalar);

sub FETCH {
my $self = shift;
print "FETCH: value is " . ${$self} . "\n";
return ${$self};
}

sub STORE {
my $self = shift;
my $val = shift;
print "STORE: old value is " . ${$self} . "\n";
${$self} = $val;
print "STORE: new value is " . ${$self} . "\n";
return ${$self};
}

package main;

my $var;
tie $var, 'Traced::Var';

$var = 42;
print "$var\n";

$var = "The answer";
print "$var\n";

__END__

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com