in reply to a referencable array slice (so assigning to it modifes the original)

Always better to wrap in a subroutine.
use Data::Dump qw(dump); my @dna = qw(A T T G C); print +(dump \@dna),$/; my @view; make_view( \@dna, 1, \@view, 0 ); make_view( \@dna, 2, \@view, 1 ); #mutate $view[0] = 'x'; $view[1] = 'x'; print +(dump \@dna), $/; make_view( \@dna, 4, \@view, 0 ); print +(dump \@dna), $/; # print ["A", "T", "x", "G", "x"] sub make_view { my ($arr, $idx1, $view, $idx2) = @_; tie $view[$idx2], 'Overridden', sub : lvalue { $arr->[$idx1] }; return; } { package Overridden; sub TIESCALAR { my ($class, $item) = @_; return bless \$item, $class; } sub FETCH { my $self = shift; ${$self}->(); } sub STORE { my $self = shift; my ($val) = @_; ${$self}->() = $val; } }

But, that's what I would do.


My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
  • Comment on Re: a referencable array slice (so assigning to it modifes the original)
  • Download Code

Replies are listed 'Best First'.
Re^2: a referencable array slice (so assigning to it modifes the original)
by ikegami (Patriarch) on Jun 12, 2008 at 20:25 UTC
    If you're going to use tie, you might as well make the following work
    my @a = qw( a b c d e ); make_view( \my @v, \@a, 2, 2 ); # @v -> splice( @a, 2, 2 ); @v = qw( x y z ); print( "@a\n" ); # a b x y z e

    similar to

    my $a = 'abcde'; substr( $a, 2, 2 ) = 'xyz'; print( "$a\n" ); # abxyze

    By the way, tie $view[$idx2], ... should be tie $view->[$idx2], ... in your code.