Personal tools

Poor man's here document

From HaskellWiki

Revision as of 18:27, 16 April 2007 by BrettGiles (Talk | contribs)

Jump to: navigation, search
main = do
  doc <- here "DATA" "Here.hs" [("variable","some"),("substitution","variables")]
  putStrLn doc
  html <- here "HTML" "Here.hs" [("code",doc)]
  putStrLn html
here tag file env = do
  txt <- readFile file
  let (_,_:rest) = span (/="{- "++tag++" START") (lines txt)
      (doc,_) = span (/="   "++tag++" END -}") rest
  return $ unlines $ map subst doc
    subst ('$':'(':cs) = case span (/=')') cs of 
      (var,')':cs) -> maybe ("$("++var++")") id (lookup var env) ++ subst cs
      _ -> '$':'(':subst cs
    subst (c:cs) = c:subst cs
    subst "" = ""
this is a poor man's here-document
with quotes ", and escapes \, 
and line-breaks, and layout
without escaping \" \\ \n,
without concatenation.
oh, and with $(variable) $(substitution), $(too).
   DATA END -}
<head><title>very important page</title></head>
   HTML END -}

See Also

Poor Man's Heredoc, as originally posted by Claus Reinke to Haskell Cafe