On Jun 13, 10:23 am, [EMAIL PROTECTED] (Gian Sartor) wrote:
> Hi All,
>
> I have a list in the following format ->
>
> room
> surname
> firstnames
>
> What I would like to is read the file into an array and combine the
> firstname and surname onto the same line and ignore the room. Below is
> an example of what I want to do ->
>
> @line = <>;
> $surname = $line[1];
> chomp ($surname);
> $fname = $line[2];
> chomp ($fname);
> print "$surname, $fname\n";
>
> this needs to loop through the array till the end but on each loop the
> $surname and $fname elements need to increment by 3, so the next time
> the loop runs it will look something like this ->
>
> @line = <>;
> $surname = $line[4];
> chomp ($surname);
> $fname = $line[5];
> chomp ($fname);
> print "$surname, $fname\n";
>
> I would like to end up with a list of names only, eg ->
>
> surname, firstname
> surname, firstname
>
> i would be grateful if someone could point me in the right direction on
> this one. TIA.

I wouldn't bother reading the file into an array at all.  Seems
wasteful.  Instead, read from your file, and let Perl keep track of
the line number for you.  When the line number is one more than a
multiple of 3, ignore it.  When it's two more than a multiple of
three, print it followed by a comma.  When it is a multiple of three,
print it followed by a newline.

#!/usr/bin/env perl
use strict;
use warnings;
while (my $line = <DATA>) {
   next if $. % 3 == 1;
   chomp $line;
   print "$line, " if $. % 3 == 2;
   print "$line\n" if $. % 3 == 0;
}
__DATA__
living room
Smith
John
Kitchen
Jones
Jimmy
Bedroom
Brady
Marcia


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to