Ammended csv to use a global var for default delimiter. Also removed dependency on vars

db4
Phil Dawes 2008-08-05 10:36:13 +01:00
parent 45154c9a97
commit 14ab1c7177
1 changed files with 10 additions and 14 deletions

View File

@ -4,12 +4,16 @@
! Simple CSV Parser ! Simple CSV Parser
! Phil Dawes phil@phildawes.net ! Phil Dawes phil@phildawes.net
USING: kernel sequences io namespaces combinators unicode.categories vars ; USING: kernel sequences io namespaces combinators unicode.categories ;
IN: csv IN: csv
DEFER: quoted-field SYMBOL: delimiter
VAR: delimiter CHAR: , delimiter set-global
: delimiter> delimiter get ; inline
DEFER: quoted-field ( -- endchar )
! trims whitespace from either end of string ! trims whitespace from either end of string
: trim-whitespace ( str -- str ) : trim-whitespace ( str -- str )
@ -44,7 +48,7 @@ VAR: delimiter
: (row) ( -- sep ) : (row) ( -- sep )
field , field ,
dup delimiter> = [ drop (row) ] when ; dup delimiter get = [ drop (row) ] when ;
: row ( -- eof? array[string] ) : row ( -- eof? array[string] )
[ (row) ] { } make ; [ (row) ] { } make ;
@ -56,24 +60,17 @@ VAR: delimiter
row append-if-row-not-empty row append-if-row-not-empty
[ (csv) ] when ; [ (csv) ] when ;
: init-vars ( -- )
delimiter> [ CHAR: , >delimiter ] unless ; inline
: csv-row ( stream -- row ) : csv-row ( stream -- row )
init-vars
[ row nip ] with-input-stream ; [ row nip ] with-input-stream ;
: csv ( stream -- rows ) : csv ( stream -- rows )
init-vars
[ [ (csv) ] { } make ] with-input-stream ; [ [ (csv) ] { } make ] with-input-stream ;
: with-delimiter ( char quot -- ) : with-delimiter ( char quot -- )
delimiter swap with-variable ; inline delimiter swap with-variable ; inline
: needs-escaping? ( cell -- ? ) : needs-escaping? ( cell -- ? )
[ "\n\"" delimiter> suffix member? ] contains? ; inline ! " [ [ "\n\"" member? ] [ delimiter get = ] bi or ] contains? ; inline ! "
: escape-quotes ( cell -- cell' ) : escape-quotes ( cell -- cell' )
[ [ dup , CHAR: " = [ CHAR: " , ] when ] each ] "" make ; inline [ [ dup , CHAR: " = [ CHAR: " , ] when ] each ] "" make ; inline
@ -85,8 +82,7 @@ VAR: delimiter
dup needs-escaping? [ escape-quotes enclose-in-quotes ] when ; inline dup needs-escaping? [ escape-quotes enclose-in-quotes ] when ; inline
: write-row ( row -- ) : write-row ( row -- )
[ delimiter> write1 ] [ escape-if-required write ] interleave nl ; inline [ delimiter get write1 ] [ escape-if-required write ] interleave nl ; inline
: write-csv ( rows outstream -- ) : write-csv ( rows outstream -- )
init-vars
[ [ write-row ] each ] with-output-stream ; [ [ write-row ] each ] with-output-stream ;