home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #30 / NN_1992_30.iso / spool / comp / lang / perl / 7384 < prev    next >
Encoding:
Text File  |  1992-12-12  |  1.6 KB  |  50 lines

  1. Newsgroups: comp.lang.perl
  2. Path: sparky!uunet!ftpbox!mothost!merlin.dev.cdx.mot.com!fendahl.dev.cdx.mot.com!mcook
  3. From: mcook@fendahl.dev.cdx.mot.com (Michael Cook)
  4. Subject: Re: C comment parser?
  5. Message-ID: <mcook.724208094@fendahl.dev.cdx.mot.com>
  6. Sender: news@merlin.dev.cdx.mot.com (USENET News System)
  7. Nntp-Posting-Host: fendahl.dev.cdx.mot.com
  8. Organization: Motorola Codex, Canton, Massachusetts
  9. References: <1268@galileo.rtn.ca.boeing.com>
  10. Date: Sun, 13 Dec 1992 00:54:54 GMT
  11. Lines: 37
  12.  
  13. meb4593@galileo.rtn.ca.boeing.com (Michael Bain) writes:
  14.  
  15. >I'm having difficulty developing the regular expression to remove C
  16. >comments from a variable (say $_) that contains a C function.  (I'm
  17. >hacking a McCabe metric and am reading in a function at a time)  
  18.  
  19. >What I have so far seems to work *most* of the time, but oftentimes it
  20. >misses an ending C comment delimiter (*/) and ends up removing a lot of
  21. >code until it reaches the last delimiter.
  22.  
  23. >Here's the RE:
  24. >    s?/\*(.*\n)*.*\*/??; # remove comments
  25.  
  26. >Does somebody have a better one that works?
  27.  
  28. Remember that RE's are maximally matched (in Perl, and most Unix tools).  If
  29. $_ has two or more comments in it, that s/// is going to delete them all in
  30. one swoop, and it'll also delete everything between the comments.
  31.  
  32. I can give you an RE that'll work.  Here:
  33.  
  34.  s%/\*([^*]|\*+[^/*])*\*+/%%g
  35.  
  36. But RE's are really the way to go.  The if comment is very big, Perl will dump
  37. core.  (I tried it.)
  38.  
  39. You can do it with index():
  40.  
  41.   $pos = 0;
  42.   while (($pos = index($_, "/*", $pos)) >= 0)
  43.   {
  44.     $end = index($_, "*/", $pos + 2);
  45.     $end >= 0 || die "unterminated comment";
  46.     substr($_, $pos, $end - $pos + 2) = '';
  47.   }
  48.  
  49. Michael.
  50.