Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re: Accessing name of tied variable in tie constructor

by tobyink (Abbot)
on Jul 10, 2013 at 15:25 UTC ( #1043493=note: print w/replies, xml ) Need Help??

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{''} = __FILE__ }; } use MyTie; our %monkey :MyTie; my %gorilla :MyTie;
package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1043493]
and the monks are chillaxin'...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2018-06-23 12:56 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (125 votes). Check out past polls.