Phoenix.pm: tieing things from afar

Scott Walters scott at illogics.org
Mon Oct 28 03:16:36 CST 2002


Andrew (et el)..

Previously I promised an example of tieing things from afar, but forgot
I promised this until I stumbled over the code. I used this magic with
the Mmap interface to graft on some logic that keeps Perl from attempting
to reallocate the memory that is mapped when it is accessed from operations
that would otherwise try to reallocate it (smaller or larger).

In this example, I have a test file that uses the toy LineBuffer module.
It creates a lexical and passes it to a function that ties it. The original
$a is modified, rather than merely the copy, because the argument array (@_)
is implemented by-reference for speed. If we read the argument into a 
variable in func() then tried to tie it, we would be working on a copy of
the variable instead of the original, and we wouldn't  be able to affect
our caller from our subroutine.

Enjoy, and as always, let me know if you have any questions.

-scott

# in a test file:

#!/usr/bin/perl
# can we tie a variable remotely?

use LineBuffer;

sub func {
  tie $_[0], LineBuffer;
}

my $a;
func($a);
$a = "hi there "; $a = "kids\n"; 
print $a;

# yes! we can! yay!


# in LineBuffer.pm:

package LineBuffer;

sub TIESCALAR {
  my $me;
  bless \$me, shift;
}

sub STORE {
  my $me = shift;
  $$me .= shift;
}

sub FETCH {
  my $me = shift;
  $$me =~ s/^(.*)\n//; return $1;
}

1;




More information about the Phoenix-pm mailing list