query in looping an array in perl

Newbie Member
2Jul2011,16:12   #1
perlbegin's Avatar
Hi there,

Greetings to the forum member,

My query:

I have an array consisting of following elements.

@arr=('finding','related','pages','on','the','worl d','wide','wide','web');

i want to lopp through this array and print three elements consecutively for each time the loop goes through the array.

i.e

for($i=0;$i<$#arr;$i++){
my $txt="$arr[$i] $arr[$i+1] $arr[$i+2]";# this prints first three elements in a variable.
print "$txt/12";
}

This outputs:

finding related pages
related pages on
pages on the
on the world
the world wide
world wide web
wide web

Here, i dont want to print the two elements combination. i.e "wide web".

i tried to use last to stop the loop 3 elements before the end of array.

i.e last if $i is equal to arr[-2].

but dont know the exact method of implementing it..


Any suggestions on it..

Thanks..
Go4Expert Member
12Jul2011,17:43   #2
sreek's Avatar
In for loop you can state second argument like this

$i <$#arr-1
Light Poster
3Aug2011,12:49   #3
ansh batra's Avatar
@a=('a','b','c','d','e');
for($i=0;$i<($#a-1),;$i++)
{
print "$a[$i] $a[$i+1] $a[$i+2]\n";
}
just change the for condition i.e i<(length-1)