http://www.perlmonks.org?node_id=1043493


in reply to Accessing name of tied variable in tie constructor

As mentioned above, I don't think it's possible. The solution mentioned by Eily; to avoid people using your tie packages directly, and provide them with a wrapper sub which captures the name of the tied variable and passes it as an argument to tie is probably the best thing to do.

Here's about as elegant as I could make it, but this solution is limited to package variables (i.e. our, not my)...

#!/usr/bin/env perl use v5.14; package MyTie { use Attribute::Handlers; use Tie::Hash (); use base 'Tie::StdHash'; sub TIEHASH { my $class = shift; warn "Tied hash: @_!!!\n"; return $class->SUPER::TIEHASH(@_); } sub UNIVERSAL::MyTie :ATTR(HASH) { (my $name = ref $_[1] ? *{$_[1]} : $_[1]) =~ s/^\*?/%/; tie %{$_[2]}, 'MyTie', $name; } BEGIN { $INC{'MyTie.pm'} = __FILE__ }; } use MyTie; our %monkey :MyTie; my %gorilla :MyTie;
package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name