Think about Loose Coupling | |
PerlMonks |
Re: Performing Mathematical Operation on Specific Column of text Fileby aaron_baugher (Curate) |
on May 14, 2015 at 23:34 UTC ( [id://1126712]=note: print w/replies, xml ) | Need Help?? |
The first thing to recognize is that your program will need to see every line of the input before it begins writing the output, since it has to see all the frequencies before it can calculate their average so it can be applied to each line. So you'll need to either: 1. Loop through the input file twice, accumulating numbers on the first time through, then making the edits and printing the output on the second time through. 2. Loop through the input file once, but save each line in an array while you do the calculations, so that your second loop can go through the array instead of hitting the filesystem again. I'd say the second solution will generally be the best unless the file is so large that putting it all in an array will cause memory problems. So let's do that. This loops through the file, adding the frequencies to an accumulator ($total) when a line matches the pattern, keeping track of how many ($howmany) frequencies it adds. Those two values will be divided to get the mean. It also saves each line in an array, along with a flag ($fixlater) to show whether that line is one containing a frequency. That way when I loop through the lines again, I don't have to split the ones that don't contain a frequency to change; the other lines can just be printed out. This does literally what you said: subtracts the mean from each frequency. Since the mean is negative, subtracting it actually adds a positive, which may or may not be what you really want. If it's not, try to describe what you really want in more detail, and give us a couple examples of input and output frequencies.
Aaron B.
In Section
Seekers of Perl Wisdom
|
|