0

I was wondering if someone could help me better understand what this given code to parse a text file is doing.

  while ($line = <STDIN>) {
    @flds = split("\t", $line);
    foreach $fld (@flds) {
        if ($fld =~ s/^"(.*)"$/\1/) {
            $fld =~ s/""/"/g;
        }
    }
    print join("\t", @flds), "\n";
}

We are given this block of code as a start to parse a text file such as.

Name    Problem #1  Comments for P1 E.C. Problem    Comments    Email
Park, John  17  Really bad. 5       [email protected]
Doe, Jane   100 Well done!  0   Why didn't you do this? [email protected]
Smith, Bob  0       0       [email protected]

...which will be used to set up a formatted output based on the parsed text.

I'm having trouble fully understanding how the block of code is parsing and holding the information so that I can know how to access certain parts of the information I want. Could someone better explain what the above code is doing at each step?

1 Answer 1

1

This is actually looks kind of a really crappy way to parse a CSV file.

while ($line = <STDIN>) { #read from STDIN 1 line at a time.
    @flds = split("\t", $line);  #Split the line into an array using the tab character and assign to @flds
    foreach $fld (@flds) {  #Loop through each item/column that's in the array @fld and assign the value to $fld
        if ($fld =~ s/^"(.*)"$/\1/) {  #Does the column have a string that is surrounded in quotes?  If it does,  replace it with the string only.
            $fld =~ s/""/"/g; #Replace any strings that are only two double quotes.
        }
    }
    print join("\t", @flds), "\n";  #Join the string back together using the tab character and print it out.  Append a line break at the end.
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, so this block of code isn't doing much more than changing a bit of the formatting of the text and rejoining it back together with tab separated values correct?
Better if you put the explanation outside the code instead of commenting inside the code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.