s_gaurav1091 has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, Writting after a long time and once again with some problem.I am working on a script in which the requirement is such that I have to insert a new line after every even elements starting from zero. for example an array is there with some data now I have to insert a new line after zero then after second element and then after fourth element and so on... Can anyone suggest what I should do???plz help
  • Comment on inserting a new line after some elemnts in an array

Replies are listed 'Best First'.
Re: inserting a new line after some elemnts in an array
by duff (Parson) on Feb 08, 2006 at 06:25 UTC

    Use modulo arithmetic to decide which elements are even:

    for my $i (0..$#array) { print $array[$i]; print "\n" if $i % 2 == 0; }
    Change the details to match your specific problem, but using % is usually what you want.
Re: inserting a new line after some elemnts in an array
by holli (Abbot) on Feb 08, 2006 at 07:21 UTC
    for (my $i=0; $i<@array; $i+=2 ) { $array[$i] .= "\n"; }


    holli, /regexed monk/
Re: inserting a new line after some elemnts in an array
by ysth (Canon) on Feb 08, 2006 at 09:52 UTC
    It's not clear whether "insert a new line after every even element" means insert a newline character at the end of each even element, or insert a new element (a newline) after each previously even element. While you probably mean the former, a solution to the latter is:
    for my $i (reverse(0..$#array/2)) { splice(@array, 2*$i+1, 0, "\n"); }