As mentioned in other answers, tie is applied to containers and not to values, so there is no way to assign a bound variable to another variable and save the associated properties.
Since there is no assignment, you need to pass the container to the GetThing routine. You can do this by reference as follows:
use strict; use warnings; main(); sub GetThing{ tie ${$_[1]}, 'mything', $_[0]; } sub main { my %m; GetThing('Fred' => \$m{pre}); print "1\n"; print $m{pre}; print "2\n"; print $m{pre}; print "3\n"; } package mything; require Tie::Scalar; my @ISA = qw(Tie::StdScalar); sub TIESCALAR { my $class = shift; bless { name => shift || 'noname', }, $class; } sub FETCH { my $self = shift; print "ACCESS ALERT!\n"; return " NAME: '$self->{name}'\n"; }
which produces the correct conclusion.
However, if you want to keep the assignment, you will need to use overloading, which applies to values ββ(actually to objects, but they themselves are values). Without detailed information on the purpose, it is difficult for you to give a complete answer, but this will meet your stated requirements:
use strict; use warnings; main(); sub GetThing{ return mything->new( shift ); } sub main { my %m; $m{pre} = GetThing('Fred'); print "1\n"; print $m{pre}; print "2\n"; print $m{pre}; print "3\n"; } package mything; sub new { my $class = shift; bless { name => shift || 'noname', }, $class; } use overload '""' => sub {
Both connections and overloads can get complicated, so read through all the documentation if something is unclear.
source share