Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As mentioned in other answers, <code>tie</code> applies to containers, and not to values, so there is no way to assign a tied variable to another variable and retain the tied properties.</p> <p>Since assignment is out, you need to pass the container into the <code>GetThing</code> routine. You can do this by reference as follows:</p> <pre><code>use strict; use warnings; main(); sub GetThing{ tie ${$_[1]}, 'mything', $_[0]; } sub main { my %m; GetThing('Fred' =&gt; \$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 =&gt; shift || 'noname', }, $class; } sub FETCH { my $self = shift; print "ACCESS ALERT!\n"; return " NAME: '$self-&gt;{name}'\n"; } </code></pre> <p>which produces the correct output.</p> <p>However, if you want to retain the assignment, you will need to use overloading, which applies to values (actually to objects, but they themselves are values). Without more detail on your intended purpose it is hard to give a complete answer, but this will meet your stated requirements:</p> <pre><code>use strict; use warnings; main(); sub GetThing{ return mything-&gt;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 =&gt; shift || 'noname', }, $class; } use overload '""' =&gt; sub { # '""' means to overload stringification my $self = shift; print "ACCESS ALERT!\n"; return " NAME: '$self-&gt;{name}'\n"; }; </code></pre> <p>Both ties and overloads can get complicated, so read through all of the documentation if anything is not clear.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload