Created
April 18, 2014 15:06
-
-
Save breezhang/11048935 to your computer and use it in GitHub Desktop.
perl tie %{}' '@{}'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use feature ":5.14"; | |
use Data::Dumper::Concise; | |
package two_refs; | |
use overload '%{}' => \&gethash, '@{}' => sub { ${ shift() } }; | |
sub new { | |
my $p = shift; | |
bless \[@_], $p; | |
} | |
sub gethash { | |
my %h; | |
my $self = shift; | |
tie %h, ref $self, $self; | |
\%h; | |
} | |
sub TIEHASH { | |
use Data::Dumper::Concise; | |
my $p = shift; | |
my $q = shift; | |
bless \$q, $p; | |
} | |
my %fields; | |
my $i = 0; | |
$fields{$_} = $i++ foreach qw{zero one two three}; | |
sub STORE { | |
my $self = ${ shift() }; | |
my $key = $fields{ shift() }; | |
defined $key or die "Out of band access"; | |
$$self->[$key] = shift; | |
} | |
sub FETCH { | |
my $self = ${ shift() }; | |
my $key = $fields{ shift() }; | |
defined $key or die "Out of band access"; | |
$$self->[$key]; | |
} | |
package main; | |
my $bar = two_refs->new( 3, 4, 5, 6 ); | |
$bar->[2] = 11; | |
$bar->{two} == 11 or die 'bad hash fetch'; | |
say $bar->{two}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment