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

You should be able to achieve this with Data::Alias. I can't test it, due to my need to stick with perl 5.8.8 on win32--sigh.

use Data::Alias; use Data::Dumper; my @foo = qw( A T T G C ); alias my @view = @foo[1,2]; $view[0] = 'x'; print Dumper \@foo;


TGI says moo

  • 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 muenalan@cpan.org (Initiate) on Jun 18, 2008 at 14:06 UTC
    NEARLY PERFECT: This is really superior to my lvalue idea. It even allows to use the @view as a syntactic @foo substitute. BUT: You cannot modify the @view after creation, while the lvalue solution allows to do so.
    use strict; use warnings; use Data::Alias; use Data::Dumper; my @foo = qw( A T T G C T T G C T T C ); alias my @view = ( @foo[1,2], @foo[5,6] ); push @view, @foo[7,8]; map {$_='$'} @view; print Dumper \@foo; print "nok" if $foo[7] ne '$';

      Like I said, I can't test this, but I think I see an error in your code:

      use strict; use warnings; use Data::Alias; use Data::Dumper; my @foo = qw( A T T G C T T G C T T C ); alias my @view = ( @foo[1,2], @foo[5,6] ); alias push @view, @foo[7,8]; # Added alias here. map {$_='$'} @view; print Dumper \@foo; print "nok" if $foo[7] ne '$';

      You added copies of $foo[7] and $foo[8] to @view. So you wound up with something like:

      @view |- 0: alias $foo[1] |- 1: alias $foo[2] |- 2: alias $foo[5] |- 3: alias $foo[6] |- 4: 'G' \- 5: 'C'
      When you wanted:
      @view |- 0: alias $foo[1] |- 1: alias $foo[2] |- 2: alias $foo[5] |- 3: alias $foo[6] |- 4: alias $foo[7] \- 5: alias $foo[8]

      I haven't been able to play with this, but it feels like you need to think about each scalar as either a normal value or an alias--unless you are working with whole aggregate aliases, in which case the aggregate is aliased. If my understanding is correct, in the example above we are not using whole aggregate aliases (just a slice), so individual aliases are assigned to @view.


      TGI says moo

        Your right. Corrected it, but still same problem.
        use strict; use warnings; use Data::Alias; use Data::Dumper; my @foo = qw( A T T G C T T G C T T C ); alias my @view = ( @foo[1,2], @foo[5,6] ); map {$_='x'} @view; print Dumper \@foo; alias my @subview = ( @foo[7,8] ); push @view, @subview; map {$_='$'} @view; print Dumper \@foo; print "nok" if $foo[7] ne '$';
        I am not sure if an alias is something you can push and pop on thing ? So how to modify a @view once its there ?