Jan Eden wrote:
Hi,
Hello,
I had the following task: Open a file, read it and merge all pairs of lines containing
a certain number of tabs. Example:
Blablabla
abc cab bca
123 453 756
Blablabla
Blablabla
Here, lines 2 and three should be merged, while the other lines should remain
untouched. Expected result:
Blablabla
abc 123
cab 453
bca 756
Blablabla
Blablabla
While I managed to get this done, I doubt that I found a good (fast) solution. So
before I move on to the large files which have to be processed, I'd like to get your
input for a better solution.
This is how I did it:
[snip]
This should work (without reading the entire file into an array):
#!/usr/bin/perl
use warnings;
use strict;
open FILE, '<', 'file.txt' or die "Cannot open 'file.txt' $!";
open OUTFILE, '>', 'input_file2.txt' or die "Cannot open 'input_file2.txt' $!";
while ( <FILE> ) {
if ( /\t/ ) {
my $next = <FILE>;
if ( $next =~ /\t/ ) {
my @data = split /[\t\n]/, "$_$next";
my %out;
@out{ @data } = splice @data, @data / 2;
print OUTFILE "$_\t$out{$_}\n" for @data;
}
else {
print OUTFILE "$_$next";
}
}
else {
print OUTFILE;
}
}
__END__
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>