Difference between revisions of "Poor man's here document"

From HaskellWiki
Jump to navigation Jump to search
(added "heredoc" to comments, mainly so google will index that term.)
Line 48: Line 48:
   
 
See Also
 
See Also
  +
* [[String Interpolation]]
 
 
* [http://groups.google.de/group/fa.haskell/msg/bb29c1797fe19caf Poor Man's Heredoc, as originally posted by Claus Reinke to Haskell Cafe]
 
* [http://groups.google.de/group/fa.haskell/msg/bb29c1797fe19caf Poor Man's Heredoc, as originally posted by Claus Reinke to Haskell Cafe]
 
* http://en.wikipedia.org/wiki/Here_document
 
* http://en.wikipedia.org/wiki/Here_document

Revision as of 10:20, 17 April 2007

-- Poor man's heredoc / here document
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
  where
    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 "" = ""

{- DATA START

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 -}

{- HTML START

<html>
<head><title>very important page</title></head>
<body>
<verb>
$(code)
</verb>
</body>
</html>

   HTML END -}

See Also