By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,848 Members | 1,319 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,848 IT Pros & Developers. It's quick & easy.

Help with a perl problem

P: 2
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:

$ part3.txt

The output should look like:


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
  3. open  (test, "@ARGV");
  5. while (<test>) {    
  6.     m/p/gi;
  7.     print;
  8. }
  10. close (test);
Someone please lend a helping hand :)
Mar 18 '08 #1
Share this Question
Share on Google+
4 Replies

P: 2

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

Expert 2.5K+
P: 4,059
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

Expert 100+
P: 971
Check out perlre and perlrequick. Look for "Match a word boundary"

Mar 18 '08 #4

Expert 100+
P: 410
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. }
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.