Hi,
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:
#!/usr/bin/perl -w
use strict;
my (@merge_one, @merge_two, @merge_three);
open (FILE, "file.txt") or die "Cannot open the input file";
my @input_file = <FILE>;
foreach (0..$#input_file) {
chomp $input_file[$_];
my $next = $_+ 1;
chomp $input_file[$next] if $input_file[$next];
if ($input_file[$_] =~ m/\t/ && $input_file[$next] =~ m/\t/) {
@merge_one = split /\t/, $input_file[$_];
@merge_two = split /\t/, $input_file[$next];
for (0..$#merge_two) {
$merge_three[$_] = $merge_two[$_] . " " . $merge_one[$_];
}
$input_file[$_] = join "\n", @merge_three;
print $input_file[$_], "\n\n";
$input_file[$next] = '';
(@merge_one, @merge_two, @merge_three) = ();
}
}
my $output = join "\n", @input_file;
open (OUTFILE, ">input_file2.txt");
print OUTFILE $output;
Grateful for any suggestion,
Jan
--
There's no place like ~/
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>