foreach my $element ( @array ) { ...... }
####
my @newlist = map { ....... } @array;
####
foreach my $idx ( 0 .. $#array ) {
#do something with $array[$idx];
}
####
my @newlist = map { # do something with $array[$_] } 0 .. $#array;
####
package IndexedArray;
use strict;
our $VERSION = '0.50';
sub TIEARRAY {
my $class = shift;
bless { ARRAY => [], INDEX => 0 }, $class;
}
sub FETCHSIZE {
my $self = shift;
$self->{INDEX} = 0;
scalar @{ $self->{ARRAY} };
}
sub STORESIZE {
my( $self, $size ) = ( $_[0], $_[1]-1 );
$self->{INDEX} = 0;
$#{ $self->{ARRAY} } = $size;
}
sub STORE {
my( $self, $index, $value ) = @_;
$self->{INDEX} = $index;
$self->{ARRAY}[$index] = $value;
}
sub FETCH {
my( $self, $index ) = @_;
$self->{INDEX} = $index;
$self->{ARRAY}[$index];
}
sub CLEAR {
my( $self ) = shift;
$self->{INDEX} = 0;
@{ $self->{ARRAY} } = ();
}
sub POP {
my $self = shift;
$self->{INDEX} = 0;
pop( @{ $self->{ARRAY} } );
}
sub PUSH {
my $self = shift;
$self->{INDEX} = $#{ $self->{ARRAY} } + scalar( @_ );
push( @{ $self->{ARRAY} }, @_ );
}
sub SHIFT {
my $self = shift;
$self->{INDEX} = 0;
shift( @{ $self->{ARRAY} } );
}
sub UNSHIFT {
my $self = shift;
$self->{INDEX} = 0;
unshift( @{ $self->{ARRAY} }, @_ );
}
sub EXISTS {
my( $self, $index ) = @_;
$self->{INDEX} = $index;
exists( $self->{ARRAY}[ $index ] );
}
sub DELETE {
my( $self, $index ) = @_;
$self->{INDEX} = 0;
delete( $self->{ARRAY}[ $index ] );
}
sub SPLICE {
my( $self ) = shift;
my $size = $self->FETCHSIZE();
my $offset = @_ ? shift : 0;
$offset += $size if $offset < 0;
my $length = @_ ? shift : $size - $offset;
$self->{INDEX} = 0;
return splice( @{ $self->{ARRAY} }, $offset, $length, @_ );
}
sub which {
my $self = shift;
return $self->{INDEX};
}
sub what {
my $self = shift;
return $self->{ARRAY}[ $self->{INDEX} ];
}
sub DESTROY { }
sub EXTEND { }
1;
####
use strict;
use warnings;
use IndexedArray;
my $obj = tie my @array, 'IndexedArray';
print "First test: Store A .. F to \@array and print \@array.\n";
@array = ( 'A' .. 'F' );
print "@array\n\n";
print "Second test: Fetch \$array[3] and discover which "
. "element it was.\n"
. "$array[3] came from ", $obj->which(), ".\n\n";
print "Third test: Iterate over \@array, and discover which\n"
. "element is being accessed in each iteration.\n"
. "Use foreach in this test.\n";
iteration_test( \@array );
print "\nFourth test. Sort \@array in reverse order, and repeat "
. "the third test.\n";
@array = reverse @array;
iteration_test( \@array );
sub iteration_test {
foreach my $element ( @{ $_[0] } ) {
print "$element came from \$array["
. $obj->which()
. "].\n";
}
}