Agnello George wrote:
hi
Hello,
i have raw data that is like this in a flat file .
start
name:agnello
dob:2 april
address:123 street
end
start
name:babit
dob:13 april
address:3 street
end
start
name:ganesh
dob:1 april
address:23 street
end
i need to get the data in the following format
name:agnello, dob:23 april ,address:123 street
name:babit,dob:13 april,address:3 street
name:ganesh,dob:1 april,address:23 street
i came up with this , is there a better way to do this :
===============================
#!/usr/bin/perl
use strict;
use warnings;
open my $FH , 'data.txt' or die "cannot open file $!";
read $FH, my $string, -s $FH;
close($FH);
my @string = split ( /start/ , $string ) ;
my %data;
foreach ( @string ) {
chomp;
next if /^$/ ;
s/^ $//g;
s/end//;
my @data = split(/\n/, "$_");
foreach my $i (@data) {
print "$i,";
}
print "\n";
}
$ echo "start
name:agnello
dob:2 april
address:123 street
end
start
name:babit
dob:13 april
address:3 street
end
start
name:ganesh
dob:1 april
address:23 street
end" | perl -e'
use warnings;
use strict;
my @data = [];
while ( <> ) {
chomp;
push @{ $data[ -1 ] }, $_ if /:/;
push @data, [] if /^end/;
}
for my $record ( @data ) {
print join( ",", @$record ), "\n";
}
'
name:agnello,dob:2 april,address:123 street
name:babit,dob:13 april,address:3 street
name:ganesh,dob:1 april,address:23 street
John
--
Any intelligent fool can make things bigger and
more complex... It takes a touch of genius -
and a lot of courage to move in the opposite
direction. -- Albert Einstein
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/