2013-06-26 4 views
0

누군가이 코드가 텍스트 파일을 구문 분석하는 것을 이해하는 데 도움이 될지 궁금합니다.Perl 문자열 구문 분석 코드

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

이 코드 블록은 다음과 같은 텍스트 파일을 구문 분석하기위한 시작으로 제공됩니다.

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] 

... 구문 분석 된 텍스트를 기반으로 형식화 된 출력을 설정하는 데 사용됩니다.

내가 원하는 정보의 특정 부분에 액세스하는 방법을 알 수 있도록 코드 블록을 구문 분석하고 정보를 보유하는 방법을 완전히 이해하는 데 문제가 있습니다. 위의 코드가 각 단계에서 무엇을하는지 더 잘 설명 할 수 있습니까?

답변

1

실제로 이것은 CSV 파일을 구문 분석하는 매우 진절머리 나는 방식입니다.

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. 
} 
+0

감사합니다.이 코드 블록은 텍스트 형식을 약간 변경하고 탭으로 구분 된 값으로 다시 결합하는 것 이상을 수행하지 않습니다. – Yoink

+0

코드 내부에 설명하는 대신 설명 *을 * 외부에 배치하면 더 좋습니다. – doubleDown