use 5.012;
use warnings;
use Data::Dump;
use Data::Dumper;


package main;

my @array = (10..13,[24..29]);
ddx \@array;


my @proxy_array;

tie @proxy_array, "Proxy::TieArray", \@array;

ddx do { local $"=", "; "... IN (@{$proxy_array[4]}) ... " };
ddx do { "... IN (@{$proxy_array[4]}) ... " };

ddx \@proxy_array;
ddx \@proxy_array;
ddx tied @proxy_array;

ddx $proxy_array[0];
ddx $proxy_array[0];
ddx $proxy_array[0];
ddx $proxy_array[4];
#say Dumper $proxy_array[4];
ddx $proxy_array[4][0];
ddx $proxy_array[4][0];
ddx $proxy_array[4][0];





BEGIN {
    package Proxy::TieArray;
    use Scalar::Util qw/blessed/;
    use Carp;
    use Data::Dump;

    
    # --- 8< ---- copied from Tie::StdArray
    #sub TIEARRAY  { bless [], $_[0] }
    sub FETCHSIZE { scalar @{$_[0]->{orig}} }
    sub STORESIZE { $#{$_[0]->{orig}} = $_[1]-1 }
    sub STORE     { $_[0]->{orig}->[$_[1]] = $_[2] }
    #sub FETCH     { $_[0]->{orig}->[$_[1]] }
    sub CLEAR     { @{$_[0]->{orig}} = () }
    sub POP       { pop(@{$_[0]->{orig}}) }
    sub PUSH      { my $o = (shift)->{orig}; push(@$o,@_) }
    sub SHIFT     { shift(@{$_[0]->{orig}}) }
    sub UNSHIFT   { my $o = shift->{orig}; unshift(@$o,@_) }
    sub EXISTS    { exists $_[0]->{orig}->[$_[1]] }
    sub DELETE    { delete $_[0]->{orig}->[$_[1]] }

    sub SPLICE
    {
        my $ob  = (shift)->{orig};
        my $sz  = $ob->FETCHSIZE;
        my $off = @_ ? shift : 0;
        $off   += $sz if $off < 0;
        my $len = @_ ? shift : $sz-$off;
        return splice(@$ob,$off,$len,@_);
    }
    # --- >8 ----

    sub TIEARRAY  {
        ddx "TIEARRAY: ", 
          my ($class, $orig) = @_;

        my $self = bless {orig=>$orig}, $class;

        return $self;
    }

    sub FETCH     {
        #ddx "FETCH: ",
        my $val =  $_[0]->{orig}->[$_[1]] ;
        if (ref $val eq __PACKAGE__) {
            ddx "FETCH: ", $_[0],$_[1];
        }
        
        _proxy($val)
    }
    
    sub UNTIE    {
        #my ($obj,$count) = @_;
        #carp "untie attempted while $count inner references still exist"              if $count;
    }

    sub DESTROY {carp "DESTROY"}

    sub _proxy {
        #warn
        my $ref = ref $_[0];
        my $refref = ref \$_[0];
        my $blessed = blessed $_[0] // "UNBLESSED";
        #warn "PROXY: <$blessed> <$refref> <$ref>";
        if ( $refref eq "REF" ) {
            if ($ref eq "ARRAY") {
                tie  my @proxy_array,  __PACKAGE__,   $_[0]; 
                #return [42..45];
                return \@proxy_array;
            } else {
                return $_[0];
            }
        } elsif( $refref  eq "SCALAR" ) {
            #warn "SCALAR <$refref> <$ref>";
            return "<<$_[0]>>";
        } else {
            warn "UNKNOWN TYPE <$refref> <$ref>";
        }
    }
}






exit;


