AIM:
A tab separated file contains different strings. Some elements are identical, some are not. I would like to "concatenate" specific elements on the same line. However, in this operation I need to make changes to the specific element to separate them from each other, e.g. adding a number to the end.
INPUT (in @input):
File1 2 range-2 operation execute:error 12345444,294837,298774
File2 3 range-1 default range:error 349928,37224
...
I would like to concatenate the "field" execute:error with 12345444,294837,298774 and range:error with 349928,37224, to give this:
OUTPUT:
execute:error-1
12345444
execute:error-2
294837
execute:error-3
298774
range:error-1
349928
range:error-2
37224
PERL CODE: I was thinking of performing a foreach loop on the elements in @input, using e.g. hashes to count the number of "strings" in last "column" separated by commas, and somehow add a number (e.g. equal to the total hash -1, making a counter?). But, this is a bit over my head. How, can I get this done? I tried a bit below, but have stopped after about two hours of trying and reading and searching for similar questions. Maybe I should not use hash?
my @output = ();
foreach (@input) {
our(@F) = split('\t', $_, 0);
my @end_numbers = split(',', $F[5], 0);
%count;
foreach (@end_numbers) {
++$count{$_};
my $counts = keys %count;
my $output = $F[4] . (adding a value here, e.g. $counts -1 for each loop itteration ) "\n" . $_;
push (@output, $output);
}
}
SOLUTION: After suggestion from @ikegami.
my @output = ();
my %counts = ();
foreach (@input) {
chomp $_;
my @fields = split(/\t/, $_, 0);
for my $num (split /,/, $fields[5]) {
++$counts{$fields[4]};
my $output = $fields[4] . "_" . $counts{$fields[4]} . "\n" . $num . "\n";
push (@output, $output);
}
}