Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

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

Comment on Re: Accessing name of tied variable in tie constructor
Select or Download Code

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1043493]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2015-11-28 12:57 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (741 votes), past polls