#!/usr/bin/perl
use strict;
my @array;
#open(my $fh, "<", "../temp/out2.asc")
# or die "Failed to open file: $!\n";
my $fh=\*DATA;
while(<$fh>) {
if (/^START/../^END/){
chomp;
push @array, $_;
}
else{
if (scalar(@array)) {
print join " ", @array;
print "\n";
@array=();
}
}
}
if (scalar(@array)) {
print join " ", @array;
print "\n";
@array=();
}
close $fh;
__DATA__
START
TIME: 3
ALT: 3.1
TEMP: 4.3
END
START
TIME: 2.6
ALT: 8
TEMP: 1
END
START
TIME: 6.1
ALT: 7.2
COLOR: 43
STRENGTH: 7
TEMP: 9.3
END
Result
D:\goodies\pdhuck\down1\perl\monks>perl 1186032.pl
START TIME: 3 ALT: 3.1 TEMP: 4.3 END
START TIME: 2.6 ALT: 8 TEMP: 1 END
START TIME: 6.1 ALT: 7.2 COLOR: 43 STRENGTH: 7 TEMP: 9.3 END
Because the if .. is true as soon as it first matches and true until after the last match, you got the start and end lines in there too.
This uses a state flag to do the collection,
use strict;
my @array;
#open(my $fh, "<", "../temp/out2.asc")
# or die "Failed to open file: $!\n";
my $fh=\*DATA;
my $collect=0;
while(<$fh>) {
if (/^START/) {$collect=1;}
elsif(/^END/){
if (scalar(@array)) {
print join " ", @array;
print "\n";
@array=();
}
$collect=0;
}
elsif($collect){
chomp;
push @array, $_;
}
}
close $fh;
__DATA__
START
TIME: 3
ALT: 3.1
TEMP: 4.3
END
START
TIME: 2.6
ALT: 8
TEMP: 1
END
START
TIME: 6.1
ALT: 7.2
COLOR: 43
STRENGTH: 7
TEMP: 9.3
END
result
D:\goodies\pdhuck\down1\perl\monks>perl 1186032-b.pl
TIME: 3 ALT: 3.1 TEMP: 4.3
TIME: 2.6 ALT: 8 TEMP: 1
TIME: 6.1 ALT: 7.2 COLOR: 43 STRENGTH: 7 TEMP: 9.3
More like what you wanted
But what if you wanted to save it all till the end of the file loop
use strict;use warnings;
my $array=[];
#open(my $fh, "<", "../temp/out2.asc")
# or die "Failed to open file: $!\n";
my $fh=\*DATA;
my $collect=0;
my $AoA=[];
while(<$fh>) {
if (/^START/) {$collect=1;}
elsif(/^END/){
if (scalar(@$array)) {push @$AoA,$array;}
$array=[];
$collect=0;
}
elsif($collect){
chomp;
push @$array, $_;
}
}
for my $a (@$AoA) {
print join(' ',@$a)."\n";
}
close $fh;
__DATA__
START
TIME: 3
ALT: 3.1
TEMP: 4.3
END
START
TIME: 2.6
ALT: 8
TEMP: 1
END
START
TIME: 6.1
ALT: 7.2
COLOR: 43
STRENGTH: 7
TEMP: 9.3
END
Result
D:\goodies\pdhuck\down1\perl\monks>perl 1186032-c.pl
TIME: 3 ALT: 3.1 TEMP: 4.3
TIME: 2.6 ALT: 8 TEMP: 1
TIME: 6.1 ALT: 7.2 COLOR: 43 STRENGTH: 7 TEMP: 9.3
same result as -b but it was saved up into an array o arrays until the end of the input file and printed then.
|