How can I correctly calculate the lengths of fields in a CSV dcoument using Perl? -
I have a datas and a simple while
is to perform an operation with a Perl script here dataset Is a small withdrawal from:
The script should calculate different fields from each ,
, and store the highest values in an array.
However, savings do not work properly. Here's a part of the code:
@maxl = Map length, @ter ms; While (`<{INFILE & gt;`} {$ _ = ~ s / [\ "\ n] // g; @terms = split / $ sep /, $ _; @lengths = map length, @ter ms; ($ K = 0, $ k & lt; = $ # terms, $ k ++) {if ($ length [$ k]> $ maxl [$ k]) {$ maxl [$ k] = The $ lenghts [$ k];}} print uses "partitions" before the "@landies \ n";}
code where this dataset I use a print
command to see the values of the operation:
1 3 7 4 4 4 1 1 5
While in loop I see other values I use another
print
statement for, I get:
1 3 4 6 4 4 4 1 1 4 1 3 5 4 4 1 4 4 1 1 4 1 3 8 4 4 4 4 1 1 4 1 3 12 4 4 4 4 1 1 4 1 3 7 4 4 4 1 1 1 1 3 4 4 4 4 1 1 4 1 3 4 4 4 4 4 4 1 1 4 1 3 16 5 4 4 4 1 1 4 2 3 4 5 3 4 4 1 1 4 2 3 7 4 4 4 1 1 4 2 3 4 4 4 4 1 4 4 4 4 4 4 1 4 4 4 4 4 4 4 4 1 4 4 4 1 1 4 4 3 4 4 4 1 1 1 4
Fourth column e.g. Obviously the value is greater than 3. While
the loop should save the highest values and move those values to @maxl
.
What was wrong?
There is a typo here for the beginning from comma Consider using it for more reliable parsing of separated data (this can also handle other separators): for commas in the loop are incorrect
for
($ k = 0, $ k
$ maxl [$ k] = $ lenghts [$ k];
(which is 'strict use')
#! / Usr / bin / perl string; warning Use: Text: Use CSV; my $ csv = Text :: CSV- & gt; New (); My @ Max_Lambels; while (my $ line = & lt; INFILE & gt;) {die Unable to parse "$ line '' 'as long as $ csv-> parse ($ line); My @column_lengths = map {length} $ csv-> Field (); My $ i (0 .. $ $ Column_lengths {$ column_lengths [$ i] & gt; ($ max_lengths [$ i] || 0)) {$ max_lengths [$ i] = $ column_lengths [$ i];}}} Print " Maximum lens for each field: @Max_Lambi \ n ";
Comments
Post a Comment