Saturday, November 26, 2011

One-line here-documents

Many of the popular languages nowadays offer here-documents as a solution to making a string out of an unescaped text. This works great for large chunks of text but it becomes too cluttered and verbose when one wants a one-line string; in all languages I know that offer here-documents, one would have to use at least two (three?) lines to write one line of unescaped text.

For example, here's a one-line heredoc in Ruby:

my_string = <<HERE.strip
This "," that
HERE

# my_string => "This \",\" that\n"

The .strip right after <<HERE is necessary to avoid a nagging trailing newline that ruby adds to every heredoc.

So as you can see, it takes three lines - one to start the heredoc, one for the text, one to end the heredoc.

I have often wanted to have a "here-line" function to be able to do just that. As far as I know that is something completely impossible to write in any of those popular languages we're talking about - they don't give you control over the lexer.

Factor does:

USING: lexer multiline.private namespaces sequences ;

: rest-of-line ( -- seq )
lexer get [ line-text>> ] [ column>> ] bi tail "" like ;

SYNTAX: HERELINE:
lexer get skip-blank
rest-of-line suffix!
lexer get next-line ;

! sample usage ( can't be used in the same file as the SYNTAX: line above
! -- if using scratchpad, copy&paste above first, then this separately )
HERELINE: This "," that
dup . print

"This \",\" that"
This "," that

No comments:

Post a Comment