Maverick
Maverick

Reputation: 587

Text file Operation in Perl

I have a text file that looks like this:

Id:001;status:open;Id:002;status:open;Id:003;status:closed;
Id:004;status:open;Id:005;status:closed;Id:006;status:open;
.... 
....

Here is my code:

#!/usr/bin/perl -w
use strict;

open IN, "<", "ABC.txt" 
    or die"Can not open the file $!";

my @split_line;           
while(my $line = <IN>) {

    @split_line = split /;/, $line;

    for (my $i = 0; $i <= $#split_line; $i++) {

        print "$split_line[$i]"." "."$split_line[$i+1]\n";  
    }
} 

Actual o/p:

Id:001 status:open
status:open Id:002
Id:002 status:open
status:open Id:003
Id:003 status:closed
status:closed 
......
......

Expected o/p is:

Id:001      status:open
Id:002      status:open
.....
....

I have no idea why it outputs the other lines. Can any body give help me with this?

Hey I am so sorry, for this but I have to modify the Output:

Actually the output is now like

**Id        Status**
001       open
002       open
...

Can some one please help me out here?

Upvotes: 1

Views: 198

Answers (1)

RobEarl
RobEarl

Reputation: 7912

Change your loop iterator to $i+=2. As you're only incrementing by 1 you're getting some values output again on the next loop.

for (my $i = 0; $i <= $#split_line; $i += 2) {

    print "$split_line[$i]"." "."$split_line[$i+1]\n";
}

Upvotes: 2

Related Questions