perl - How to increment (alter) a string for each passage in a loop -
aim:
a tab separated file contains different strings. elements identical, not. "concatenate" specific elements on same line. however, in operation need make changes specific element separate them each other, e.g. adding number end.
input (in @input):
file1 2 range-2 operation execute:error 12345444,294837,298774 file2 3 range-1 default range:error 349928,37224 ...
i concatenate "field" execute:error 12345444,294837,298774 , range:error 349928,37224, 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: thinking of performing foreach loop on elements in @input, using e.g. hashes count number of "strings" in last "column" separated commas, , somehow add number (e.g. equal total hash -1, making counter?). but, bit on head. how, can done? tried bit below, have stopped after 2 hours of trying , reading , searching similar questions. maybe should not use hash?
my @output = (); foreach (@input) { our(@f) = split('\t', $_, 0); @end_numbers = split(',', $f[5], 0); %count; foreach (@end_numbers) { ++$count{$_}; $counts = keys %count; $output = $f[4] . (adding value here, e.g. $counts -1 each loop itteration ) "\n" . $_; push (@output, $output); } }
solution: after suggestion @ikegami.
my @output = (); %counts = (); foreach (@input) { chomp $_; @fields = split(/\t/, $_, 0); $num (split /,/, $fields[5]) { ++$counts{$fields[4]}; $output = $fields[4] . "_" . $counts{$fields[4]} . "\n" . $num . "\n"; push (@output, $output); } }
the value trying concatenate $count{$_}
.
my %counts; while (<>) { chomp; ($class, $nums) = ( split /\t/ )[4,5]; $num (split /,/, $nums) { ++$counts{$class}; print "$class-$counts{$class}\n"; print "$num\n"; } }
or save line:
printf "%s-%s\n", $class, ++$counts{$class}; printf "%s\n", $num;
if want count reset every line of input, use my $count;
inside of outer loop instead of my %counts;
, , use $count
instead of $counts{$class}
.
Comments
Post a Comment