home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #31 / NN_1992_31.iso / spool / comp / lang / perl / 7604 < prev    next >
Encoding:
Text File  |  1992-12-23  |  1.7 KB  |  57 lines

  1. Newsgroups: comp.lang.perl
  2. Path: sparky!uunet!spool.mu.edu!wupost!emory!sol.ctr.columbia.edu!eff!enterpoop.mit.edu!linus!philabs!acheron!scifi!watson!yktnews!admin!simon!cwalker
  3. From: cwalker@rchland.vnet.ibm.com (Cary Walker)
  4. Subject: Dynamic grepping
  5. Sender: news@rchland.ibm.com
  6. Message-ID: <1992Dec23.155457.15647@rchland.ibm.com>
  7. Date: Wed, 23 Dec 1992 15:54:57 GMT
  8. Disclaimer: This posting represents the poster's views, not necessarily those of IBM
  9. Nntp-Posting-Host: simon.rchland.ibm.com
  10. Organization: IBM Rochester
  11. Lines: 44
  12.  
  13. Is there a way to have the string that grep checks for stored in a variable?  For
  14. example, say I wanted to find those lines in an array of lines that contained
  15. digits.  Could I store the regular expression, \d,  in a variable and have grep
  16. check the array against that?
  17.  
  18. Here's a small sample program to express my point:
  19.  
  20. #!/usr/bin/perl
  21.  
  22. unshift(@checkstrs, "1111foo222");
  23. unshift(@checkstrs, "foofoo");
  24. $grepstr="\d";
  25.  
  26. @digitsfound1 = grep(/$grepstr/, @checkstrs);
  27. @digitsfound2 = grep("$grepstr", @checkstrs);
  28. @digitsfound3 = grep('$grepstr', @checkstrs);
  29. @digitsfound4 = grep(/\d/, @checkstrs);
  30.  
  31. foreach $digitfound1(@digitsfound1) {
  32.         print "1st run=$digitfound1\n";}
  33. foreach $digitfound2(@digitsfound2) {
  34.         print "2nd run=$digitfound2\n";}
  35. foreach $digitfound3(@digitsfound3) {
  36.         print "3rd run=$digitfound3\n";}
  37. foreach $digitfound4(@digitsfound4) {
  38.         print "4th run=$digitfound4\n";}
  39. The output is:
  40.  
  41. 2nd run=foofoo
  42. 2nd run=1111foo222
  43. 3rd run=foofoo
  44. 3rd run=1111foo222
  45. 4th run=1111foo222
  46.  
  47. The 4th grep expression worked like I wanted it to but the regular expression is
  48. explicit there and not in a variable.
  49.  
  50. I've looked into the eval function but to no avail.
  51.  
  52. Thanks!
  53.  
  54. -Cary
  55.  
  56.  
  57.