CSV
csv 값은 유효한 CSV를 담은 텍스트예요. 쉼표로 나뉜 셀로 이루어진 행이 있고, 한 줄에 한 행이 들어가요. ```csv 블록으로 쓰거나, 변수에 csv 타입과 따옴표로 묶은 텍스트를 지정할 수 있어요. 어느 쪽이든 CSV로 읽히지 않는 줄(예: 닫히지 않은 따옴표)은 작성한 자리에서 편집기와 스크립트 실행 시 모두 오류가 나요.
<const name="prices">```csv
fruit,price
apple,3
plum,5
```</const>
<let name="totals" type="csv" value="'month,total'" />const $prices = ```csv
fruit,price
apple,3
plum,5
```
$totals: csv = 'month,total'첫 줄에는 보통 열 이름이 있어요. .headers이 이를 읽어요:
<echo value="$prices.headers" /> <!-- ['fruit', 'price']: the first line names the columns -->echo $prices.headers // ['fruit', 'price']: the first line names the columns셀 읽기
->cells()은 csv의 셀을 읽어요. 단독으로 쓰거나 rows 플래그와 함께 쓰면 모든 행을, columns와 함께 쓰면 모든 열을 돌려줘요. row:는 한 행을, column:는 한 열을 골라요. 행은 0부터 세고(-1은 마지막 행), 열은 헤더 이름이나 0부터 센 번호로 지정해요:
<echo value="$prices->cells()" /> <!-- [{ fruit: 'apple', price: 3 }, { fruit: 'plum', price: 5 }]: every row -->
<echo value="$prices->cells(columns)" /> <!-- { fruit: ['apple', 'plum'], price: [3, 5] }: every column, by its header -->
<echo value="$prices->cells(row: 0).fruit" /> <!-- 'apple': the header line names each row's keys -->
<echo value="$prices->cells(column: 'price')" /> <!-- [3, 5]: the cells under the price header -->
<echo value="$prices->cells(row: 1, column: 'price')" /> <!-- 5: where plum's row meets the price column -->echo $prices->cells() // [{ fruit: 'apple', price: 3 }, { fruit: 'plum', price: 5 }]: every row
echo $prices->cells(columns) // { fruit: ['apple', 'plum'], price: [3, 5] }: every column, by its header
echo $prices->cells(row: 0).fruit // 'apple': the header line names each row's keys
echo $prices->cells(column: 'price') // [3, 5]: the cells under the price header
echo $prices->cells(row: 1, column: 'price') // 5: where plum's row meets the price columnrow:과 rows는 둘 중 하나만 고를 수 있고, column:와 columns도 마찬가지예요. 한 쌍에서 하나씩은 함께 쓸 수 있어요: ->cells(rows, column: 'price')는 모든 행의 가격으로, ->cells(column: 'price')와 같아요. 한 행과 모든 열은 함께 쓸 수 없어요. 행의 셀은 이미 하나의 열에 해당하기 때문에, ->cells(row: 0, columns)은 ->cells(row: 0)을 쓰라는 오류를 내요.
숫자로 적힌 셀은 숫자로 나와서 바로 더할 수 있어요. 그 밖의 셀은 텍스트이고, 007처럼 앞자리 0이 사라지면 안 되는 코드도 텍스트로 읽어요.
첫 줄의 셀이 모두 숫자가 아니면 첫 줄은 헤더예요. 모두 숫자라면 데이터로 읽어요. 퍼즐 입력이나 측정값에는 보통 헤더가 없어서 모든 줄이 숫자 행이에요. 첫 줄이 어느 쪽인지 애매하면 header 또는 not header를 지정하세요:
<const name="readings">```csv
387
942
945
```</const>
<echo value="$readings->cells(column: 0)->sum()" /> <!-- 2274: every line is a number, so there's no header -->
<echo value="$prices->cells(not header)->count()" /> <!-- 3: the fruit,price line is a row too -->const $readings = ```csv
387
942
945
```
echo $readings->cells(column: 0)->sum() // 2274: every line is a number, so there's no header
echo $prices->cells(not header)->count() // 3: the fruit,price line is a row too셀은 쉼표로 나뉘어요. csv에 쉼표가 없으면 탭이나 세미콜론으로 나누고, 숫자 사이의 공백으로도 나눠요. 행마다 셀 개수가 달라도 돼요:
<const name="numbers">```csv
-903 -642 -518 -585 446
692 853
```</const>
<echo value="$numbers->cells(row: 0)" /> <!-- [-903, -642, -518, -585, 446]: spaces split the numbers -->
<echo value="$numbers->cells(row: -1)->sum()" /> <!-- 1545: the last row, 692 + 853 -->
<echo value="$numbers->cells(column: 2)" /> <!-- [-518]: the third number of each row long enough to have one -->
<echo value="$numbers->cells(columns)" /> <!-- [[-903, 692], [-642, 853], [-518], [-585], [446]] -->const $numbers = ```csv
-903 -642 -518 -585 446
692 853
```
echo $numbers->cells(row: 0) // [-903, -642, -518, -585, 446]: spaces split the numbers
echo $numbers->cells(row: -1)->sum() // 1545: the last row, 692 + 853
echo $numbers->cells(column: 2) // [-518]: the third number of each row long enough to have one
echo $numbers->cells(columns) // [[-903, 692], [-642, 853], [-518], [-585], [446]]헤더가 없으면 열이 닿지 않는 짧은 행은 건너뛰어요. 그래서 column: 2은 세 번째 숫자가 있는 모든 행의 값을 주고, columns는 뒤쪽 열일수록 짧은 목록을 줘요. 어떤 행도 닿지 않는 열은 오류예요. 헤더가 있으면 모든 행에 모든 열이 있으므로, 여기서 짧은 행은 오류예요.
as:에 타입을 주면 결과가 검사되고 그 타입으로 변환돼요. 행은 타입의 레코드가 되고, 셀은 그 필드 타입으로 변환돼요:
<type name="Price">
<field name="fruit" type="string" />
<field name="price" type="int" />
</type>
<let name="cheapest" value="$prices->cells(as: Price)->min(by: fn(row) => $row.price)" />
<echo value="$cheapest.fruit" /> <!-- 'apple': 3 is the lowest price -->type Price {
fruit: string
price: int
}
$cheapest = $prices->cells(as: Price)->min(by: fn(row) => $row.price)
echo $cheapest.fruit // 'apple': 3 is the lowest price파일이 아니에요
@read_csv은 파일을 읽으므로 file_path를 받아요. @read_csv($prices)처럼 csv 텍스트를 넘기면 오류가 나요: "'path' 인수에는 file_path가 필요하지만, 이것은 파일이 아닌 csv 텍스트입니다." 빠른 수정은 대신 csv를 직접 읽는 방법을 제안해요:
<echo value="$prices->cells()" /> <!-- the rows, read from the text itself -->echo $prices->cells() // the rows, read from the text itself->save()은 파일에 쓰고, 이름에 확장자가 없으면 .csv를 붙여요. 그런 다음 @read_csv이 그 파일을 다시 읽어요:
<do>$prices->save('prices')</do> <!-- writes prices.csv -->$prices->save('prices') // writes prices.csv