It's a tad more efficient to use perl's built-in aliasing mechanism instead of a tie, at the slight cost of using an array reference rather than an array direct.
P:\test>test3 1 2 3 4 It changed 6 So did this 8 9 10 Rate tie sub tie 473/s -- -96% sub 11689/s 2370% -- 0 0 0 -15402 -15402 -15402 -15402 -15402 0 0
#! perl -slw use strict; package Tie::Array::Slice; use Tie::Array; our @ISA = 'Tie::StdArray'; use Data::Dumper; use strict; sub FETCH { ${ $_[0]->[ $_[1] ] } } sub STORE { ref $_[2] ? $_[0]->[ $_[1] ] = $_[2] : ${ $_[0]->[ $_[1] ] } = $_[2]; } package main; use Benchmark qw[ cmpthese ]; sub aliasSlice{ return \@_ } my @a = ( 1 .. 10 ); tie my @b, 'Tie::Array::Slice'; @b = ( \( @a ) )[ 3 .. 7 ]; my $c = aliasSlice( @a[ 3 .. 7 ] ); $b[ 1 ] = 'It changed'; $c->[ 3 ] = 'So did this'; print "@a\n"; our @aliased = (0) x 10; cmpthese( -1, { tie => q[ tie my @alias, 'Tie::Array::Slice'; @alias = ( \( @aliased ) )[ 3 .. 7 ]; $_++ for @alias; ], sub => q[ my $alias = aliasSlice( @aliased[ 3 .. 7 ] ); $_-- for @$alias; ], }); print "\n@aliased"; __END__ P:\test>test3 1 2 3 4 It changed 6 So did this 8 9 10 Rate tie sub tie 473/s -- -96% sub 11689/s 2370% -- 0 0 0 -15402 -15402 -15402 -15402 -15402 0 0
In reply to Re: Re: reference to an array slice?
by BrowserUk
in thread reference to an array slice?
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |