Agnello,
Here is one way to do it
[code]
use strict;
use warnings;
use subs qw/get_single_record/;
my $start = '^start$';#Start pattern
my $end = '^end$';#End pattern
while( my @record = get_single_record( *DATA, $start, $end )){
chomp @record;
print join ',', @record, "\n";
#You can use say instead if your are on version 5.10 and higher
}
sub get_single_record {
my $file = shift;#Get the file to read
my $start = shift;#Get the start pattern
my $end = shift;#Get the end pattern
my @record;
while(<$file>) {
if(/$start/ ... /$end/) {
#Skip the start and end lines
push @record, $_ unless (/$start/ || /$end/);
#Exit on $end; as we are done with one record
last if /$end/;
}
}
return @record;
}
__DATA__
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
[/code]
[output]
name:agnello,dob:2 april,address:123 street,
name:babit,dob:13 april,address:3 street,
name:ganesh,dob:1 april,address:23 street,
[/output]
best,
Shaji
-------------------------------------------------------------------------------
Your talent is God's gift to you. What you do with it is your gift back to God.
-------------------------------------------------------------------------------
________________________________
From: Agnello George <[email protected]>
To: Perl Beginners <[email protected]>
Sent: Friday, 12 July 2013 5:14 PM
Subject: grab pattern from start and end block
hi
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";
}
--
Regards
Agnello D'souza
“Happiness is not so much in having , but in sharing.
We make a living by what we get,
but we make a Life by what we Give.”