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

  1. Newsgroups: comp.lang.perl
  2. Path: sparky!uunet!psinntp!balltown!cabot!rodney
  3. From: rodney@cabot (Rodney Peck)
  4. Subject: Re: Feature request for perl V
  5. Message-ID: <1992Dec18.215039.2394@cabot.balltown.cma.COM>
  6. Sender: usenet@cabot.balltown.cma.COM
  7. Nntp-Posting-Host: cabot
  8. Organization: New York State Institute for Sebastian Cabot Studies
  9. X-Newsreader: Tin 1.1 PL4
  10. References: <62887@mimsy.umd.edu>
  11. Date: Fri, 18 Dec 1992 21:50:39 GMT
  12. Lines: 47
  13.  
  14. #!/bin/perl
  15.  
  16. @lines = (
  17. "folta@cs.umd.edu (Wayne Folta) writes:",
  18. ": Could grep have an added option/mode that would allow me to get an array",
  19. ": of indices instead of an array of items? I want to read a file into an",
  20. ": array, then do some greps in the array, some calculations, and then if",
  21. ": everything is right, make a couple of changes in the array, then write it",
  22. ": back out to the file. If I could do this:",
  23. ": ",
  24. ":    @line_numbers = grepi (/IN A/, @lines) ;",
  25. ": ",
  26. ": I'd be pretty happy. How's it sound?");
  27.  
  28. # I think the subroutine below does what you want.  I can't see any reason
  29. # to make this an internal function.  I imagine the internal version would
  30. # do roughly the same thing.
  31. #  rodney
  32. #
  33. #  here's the output of grepi looking for " array" in the above message:
  34. #
  35. # cabot> perl f
  36. # 1, 2, 3, 4
  37. # : Could grep have an added option/mode that would allow me to get an array
  38. # : of indices instead of an array of items? I want to read a file into an
  39. # : array, then do some greps in the array, some calculations, and then if
  40. # : everything is right, make a couple of changes in the array, then write it
  41.  
  42.  
  43. @line_numbers = &grepi("/ array/",@lines);
  44.  
  45. print join(", ", @line_numbers),"\n";
  46. grep ((print @lines[$_],"\n"), @line_numbers);
  47.  
  48. sub grepi {
  49. local ($exp,@ar) = @_;
  50. local (@ans,$_);
  51. local ($count) = 0;
  52.  
  53.   foreach $_ (@ar)
  54.   {
  55.     push(@ans,$count) if eval($exp);
  56.     $count++;
  57.   }
  58.   @ans;
  59. }
  60.