query in looping an array in perl

perlbegin's Avatar, Join Date: Jul 2011
Newbie Member
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..
sreek's Avatar, Join Date: Nov 2010
Go4Expert Member
In for loop you can state second argument like this

$i <$#arr-1
ansh batra's Avatar, Join Date: Jan 2010
Light Poster
@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)