Re: question on reference to array slice
- From: "attn.steven.kuo@xxxxxxxxx" <attn.steven.kuo@xxxxxxxxx>
- Date: Sun, 29 Jul 2007 17:10:36 -0700
On Jul 29, 11:58 am, Mirco Wahab <wahab-m...@xxxxxx> wrote:
Rick wrote:
In C we can store a set of pointers which point to different arrays
into an array of pointer. This way we could fast access different
array by looking it up in this pointer array. Is there anyway to do
this in Perl. I've been trying different things and no luck so far.
LIke:
@nums = (1 .. 20);
I want to store the reference to @nums[1..10] into $data[0], and the
reference to @nums[11:20] into $data[1], so that I could visit, for
example, the second set of @nums by something like $data[1][5] to get
15.
Is this possible for Perl anyway?
No
You can't do that in Perl because "arrays"
aren't continous memory blocks (C/C++),
but rather _already_ pointer arrays
(pointers to elements as array values)
with a somehow complicated management
built around.
Furthermore, you can't "jump" in the
middle of something arraylike and
expect to find a mechanism there
which treats the rest as a Perl
array.
The only way to come close is the
_copying_ of an array element range
(slice) into a new (anonymous) array,
as Gunnar has already shown.
You can try the tie function (perldoc perltie). E.g.,
package Tie::Slice;
use Tie::Array;
@ISA = qw/Tie::Array/;
sub TIEARRAY {
my $class = shift;
my $aref = shift;
my $offset = shift;
my $length = shift || (@$aref - $offset);
return bless {
AREF => $aref,
OFFSET => $offset,
LENGTH => $length,
}, $class;
}
sub FETCH {
my ($self, $index) = @_;
if ($index >= 0) {
return $self->{AREF}->[$self->{OFFSET}+$index];
} else {
my $subtracted = $self->{OFFSET} + $self->{LENGTH};
return $self->{AREF}->[$index - $subtracted];
}
}
sub FETCHSIZE {
my ($self) = @_;
return $self->{LENGTH};
}
# no methods added for writing to array (e.g., STORE, STORESIZE,
etc.).
package main;
use strict;
use warnings;
my @nums = ( 1 .. 20 );
my (@first_half, @second_half);
tie @first_half, 'Tie::Slice', \@nums, 0, 10;
tie @second_half, 'Tie::Slice', \@nums, 10;
my @data = (\@first_half, \@second_half);
print $data[1][5];
__END__
Note that changes made to @nums will be automatically
reflected in @data (but not visa-versa since I've
only implemented the methods needed for "reading" in
Tie::Slice).
--
Regards,
Steven
.
- References:
- question on reference to array slice
- From: Rick
- Re: question on reference to array slice
- From: Mirco Wahab
- question on reference to array slice
- Prev by Date: Re: question on reference to array slice
- Next by Date: Re: question on reference to array slice
- Previous by thread: Re: question on reference to array slice
- Next by thread: Re: question on reference to array slice
- Index(es):
Relevant Pages
|