Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Re: reference to an array slice?

by BrowserUk (Pope)
on Sep 26, 2003 at 11:37 UTC ( #294379=note: print w/ replies, xml ) Need Help??


in reply to Re: reference to an array slice?
in thread reference to an array slice?

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

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller
If I understand your problem, I can solve it! Of course, the same can be said for you.


Comment on Re: Re: reference to an array slice?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://294379]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (7)
As of 2014-12-29 13:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (188 votes), past polls