1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

query in looping an array in perl

Discussion in 'Perl' started by perlbegin, Jul 2, 2011.

  1. perlbegin

    perlbegin New Member

    Joined:
    Jul 2, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi there,

    Greetings to the forum member,

    My query:

    I have an array consisting of following elements.

    @arr=('finding','related','pages','on','the','world','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..
     
  2. sreek

    sreek New Member

    Joined:
    Nov 15, 2010
    Messages:
    11
    Likes Received:
    2
    Trophy Points:
    0
    In for loop you can state second argument like this

    $i <$#arr-1
     
  3. ansh batra

    ansh batra New Member

    Joined:
    Jan 17, 2010
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    student
    @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)
     

Share This Page