Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

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{'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


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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2015-07-05 05:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (60 votes), past polls