You got close
Result#!/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
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.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
This uses a state flag to do the collection,
resultuse 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
More like what you wantedD:\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
But what if you wanted to save it all till the end of the file loop
Resultuse 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
same result as -b but it was saved up into an array o arrays until the end of the input file and printed then.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
In reply to Re: Arrays & Output printing?
by huck
in thread Arrays & Output printing?
by coding1227
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |