changing the tied object

merlyn on 2003-01-04T17:49:14

Just had a discussion on IRC... thought I would write this down in case anyone else wants the conclusion.

Yes, you can indeed write to $_[0] inside one of the tie accessor callbacks (like STORE or FETCH), and change the underlying hidden tied action object.

For example, suppose you want to wrap Apache::Session, so that on first store or fetch, it does some init before becoming a real session object:

package My::Apache::Session;
sub TIEHASH {
  my $class = shift;
  bless [@_], $class; # remember real args
}
sub FETCH {
  ## DO NOT USE shift HERE
  $_[0]->my_initialization;
  $_[0] = Apache::Session->TIEHASH(@{$_[0]});
  $_[0]->FETCH($_[1]);
}
sub STORE {
  ## DO NOT USE shift HERE
  $_[0]->my_initialization;
  $_[0] = Apache::Session->TIEHASH(@{$_[0]});
  $_[0]->STORE($_[1], $_[2]);
}
sub my_initialization { ... }