home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / lang / perl / 5724 < prev    next >
Encoding:
Internet Message Format  |  1992-09-03  |  2.2 KB

  1. Path: sparky!uunet!dtix!darwin.sura.net!uvaarpa!mmdf
  2. From: dov@menora.weizmann.ac.il (Dov Grobgeld)
  3. Newsgroups: comp.lang.perl
  4. Subject: quoteSplit - Split string into array with embedded quotes
  5. Message-ID: <1992Sep4.085440.9025@uvaarpa.Virginia.EDU>
  6. Date: 4 Sep 92 08:54:40 GMT
  7. Sender: mmdf@uvaarpa.Virginia.EDU (Mail System)
  8. Reply-To: dov@menora.weizmann.ac.il
  9. Organization: The Internet
  10. Lines: 52
  11.  
  12. Here is a small useful subroutine I put together. It has probably been
  13. done before, and it has probably been posted as well. But as has been said
  14. before here, it is easier to reinvent the wheel in Perl, than to go to the
  15. junk yard looking for an old one. There is a nice use of m//g in the
  16. script, and a blasting one-liner, which to the uninitiated certainly
  17. would look like line-noise.
  18.  
  19. Enjoy!
  20.  
  21.  
  22. #############################################################################
  23. #  quoteSplit. Splits a text string into an array and allows for embedded
  24. #  quoted strings.
  25. #
  26. #  Examples (perl quoting mechanism q() used to denote input strings...)
  27. #
  28. #     q(a b c)  splits into ('a','b','c')
  29. #     q(ab,c,d) splits into ('ab','c','d')
  30. #     q('a b' c) splits into ('a b', c)
  31. #     q('that\'s', "it ") splits into ("that's", "it")
  32. #
  33. #  Dov Grobgeld
  34. #  The Weizmann Institute of Science, Israel
  35. #  Email: dov@menora.weizmann.ac.il
  36. #############################################################################
  37.  
  38. sub quoteSplit {
  39.     local($_) = $_[0];
  40. #    local(@list);
  41.  
  42.     s/\\"/\01/g; s/\\'/\02/g;   # Hide escaped quotation marks
  43.  
  44. #    @list= /"[^"]*"|'[^']*'|[^\s,]+/g;
  45. #    grep(s/^(["'])(.*)\1$/$2/ + tr/\1\2/"'/, @list);
  46. #    @list;
  47.  
  48.     # This one liner is equivalent to the the three lines above
  49.     grep(1+s/^(["'])(.*)\1$/$2/+tr/\01\02/"'/,/"[^"]*"|'[^']*'|[^\s,]+/g);
  50. }
  51.  
  52. while(<>) {
  53.     print join(":", "eSplit($_)),"\n";
  54. }
  55.  
  56. --
  57.                                                         ___   ___
  58.                                                       /  o  \   o \
  59. Dov Grobgeld                                         ( o  o  ) o   |
  60. The Weizmann Institute of Science, Israel             \  o  /o  o /
  61. "Where the tree of wisdom carries oranges"              | |   | |
  62.                                                        _| |_ _| |_
  63.                                        
  64.