home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #20 / NN_1992_20.iso / spool / comp / lang / perl / 5950 < prev    next >
Encoding:
Internet Message Format  |  1992-09-15  |  2.0 KB

  1. Path: sparky!uunet!dtix!darwin.sura.net!convex!convex!connolly
  2. From: connolly@convex.com (Dan Connolly)
  3. Newsgroups: comp.lang.perl
  4. Subject: Re: Parsing RTF
  5. Message-ID: <1992Sep15.182241.6455@news.eng.convex.com>
  6. Date: 15 Sep 92 18:22:41 GMT
  7. References: <1992Sep15.035214.13097@Trirex.COM>
  8. Sender: usenet@news.eng.convex.com (news access account)
  9. Organization: Engineering, CONVEX Computer Corp., Richardson, Tx., USA
  10. Lines: 64
  11. Nntp-Posting-Host: pixel.convex.com
  12. X-Disclaimer: This message was written by a user at CONVEX Computer
  13.               Corp. The opinions expressed are those of the user and
  14.               not necessarily those of CONVEX.
  15.  
  16. In article <1992Sep15.035214.13097@Trirex.COM> mmelling@Trirex.com(Michael Mellinger) writes:
  17. >I'm interested in writing a small RTF parser in Perl.  Given rtf text,  
  18. >like that shown below, what is the best way to extract tokens from the  
  19. >text?
  20. >
  21.  
  22. Here's some perl code that parses RTF and writes stuff that a lisp
  23. parser could digest.
  24.  
  25. #!/usr/local/bin/perl
  26. #
  27.  
  28. while(<>){
  29.     while($_ ne ''){
  30.     if(s/^\{//){    # open {
  31.         print "( ";
  32.     }elsif(s/^\}//){ # close }
  33.         print ")\n";
  34.     }elsif(s/^\\//){ # control sequence
  35.         if(s/^([a-zA-Z]+)(-?[0-9]*) ?//){ # control word
  36.         if($2 ne ''){ # with parameter
  37.             print "($1 $2) ";
  38.         }else{
  39.             print $1, " ";
  40.         }
  41.         }else{ # special control sequence
  42.         if(s/^\'//){ # hex encoded char
  43.             s/..//;
  44.             print "#x$& ";
  45.         }elsif(s/^[:{}\\]//){ # single char escape
  46.             print &lisp_string($&);
  47.         }elsif(s/^\|//){
  48.             print "rtfFormula ";
  49.         }elsif(s/^\~//){
  50.             print "rtfNoBrkSpace ";
  51.         }elsif(s/^\_//){
  52.             print "rtfNoReqHyphen ";
  53.         }elsif(s/^[\n\r]//){
  54.             print "par ";
  55.         }elsif(s/^\*//){
  56.             print "rtfOptDest ";
  57.         }else{
  58.             s/.//;
  59.             warn "look this one up: $& ", ord($&);
  60.         }
  61.         }
  62.     }else{
  63.         if(s/^\t//){
  64.         print "TAB ";
  65.         }else{
  66.         s/^[^\t\\{}]+// && print &lisp_string($&);
  67.         }
  68.     }
  69.     }
  70. }
  71.  
  72. sub lisp_string{
  73.     local($_) = @_;
  74.  
  75.     s/\n//g;
  76.     return '' if $_ eq '';
  77.     s/\"/\\\"/g;
  78.     return '"' . $_ . '" ';
  79. }
  80.