How Do I iterate through the array, yet compare the next item against the former?
You use an index, or you keep a stack
The index approach, its missing boundary checking ( ; beware of off-by-one errors
my @stuff = 0 .. 9;
for my $ix ( 0 .. $#stuff ){
my $item = $stuff[$ix];
my $prev = $stuff[$ix-1];
my $next = $stuff[$ix+1];
}
The stack approach
my @stuff = 0 .. 9;
my $lastitem = "";
for my $item ( @stuff ){
my $next = $item;
if( $item eq $lastitem ){
print "they measure up\n";
}
$lastitem = $item;
}
Oh, but you $lastitem is not an array, right
my @stuff = 0 .. 9;
my @lastitem ;
for my $item ( @stuff ){
my $next = $item;
if( @lastitem and $item eq $lastitem[-1] ){
print "they measure up\n";
}
push @lastitem, $item;
shift @lastitem while 3 == @lastitem; ### keep at most 3 last items
}
|