Skip to content

Instantly share code, notes, and snippets.

@breezhang
Created April 18, 2014 15:06
Show Gist options
  • Save breezhang/11048935 to your computer and use it in GitHub Desktop.
Save breezhang/11048935 to your computer and use it in GitHub Desktop.
perl tie %{}' '@{}'
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