469,337 Members | 6,005 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,337 developers. It's quick & easy.

Help with a perl problem

Hi everyone,

I am trying to teach myself Perl with the aid of some books I have boughten. I'm doing some exercises with regular expressions but am having some trouble, specifically with this problem:

Write a program that prints only words (not the entire line) in the file part3.txt (attached) on a word boundary that have the letter "p" or "P" in them.

The Unix command line should look like:

$ proj2_3.pl part3.txt

The output should look like:

Perl
pattern
pattern
Perl
help


The text file given is this:

CPAN stands for comprehensive Perl Archive Network.
^ and $ are used as anchors in a regular expression.
/pattern/ is a pattern match operator.
Perl is very easy to learn.
Enter 'H' or 'h' for help.


So far what I have is this:

Expand|Select|Wrap|Line Numbers
  1. #!usr/bin/env perl
  2.  
  3. open  (test, "@ARGV");
  4.  
  5. while (<test>) {    
  6.     m/p/gi;
  7.     print;
  8. }
  9.  
  10. close (test);
Someone please lend a helping hand :)
Mar 18 '08 #1
4 1369
/bump

No one has any idea about this? Is there some regular expression that can find a character and print out the word it's in?
Mar 18 '08 #2
KevinADC
4,059 Expert 2GB
The obvious way is to use the split() function and split the lines into words then check each word for /[Pp]/ instead of each line, like you are doing. But I have no idea what the book you are reading has covered so far so making specific suggestions may not be relevant to where you are in the lessons/book.

Kevin(R) ;)
Mar 18 '08 #3
eWish
971 Expert 512MB
Check out perlre and perlrequick. Look for "Match a word boundary"

--Kevin
Mar 18 '08 #4
nithinpes
410 Expert 256MB
You should also look out for '/' or '.' occuring near word boundaries. The following script will do the job.

Expand|Select|Wrap|Line Numbers
  1. #!usr/bin/env perl
  2. while (<>) {    
  3.          while(/\b[.\/]?(\w+)[.\/]?\b/g) {
  4.              $word = $1;
  5.              print "$word\n" if($word=~/^p|p$/i);
  6.        }
  7. }
  8.  
But, inorder to understand this regex better or to extend this for some other scenario, kindly go through the links posted by Kevin.
Mar 19 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

2 posts views Thread by Tomislav Lepusic | last post: by
5 posts views Thread by enkidu72 | last post: by
2 posts views Thread by geniuskanwal | last post: by
rajiv07
1 post views Thread by rajiv07 | last post: by
reply views Thread by Marylou17 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.