Question:
Updated Question: How do I search in Perl?
lamar211us
2007-03-13 10:14:49 UTC
I need to search for words in a txt file (see below) that begin with "p" and "P" and words that end with "p" and "P" and print them out. Thank the people who have helped me answer my previous question.

Text File:
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.

#!/usr/local/bin/perl
open INPUT, "while ()
{
my($line) = $_;
chomp($line);
if ($line =~ m\b\^p*\bi) {print "$&\n";}
if ($line =~ m/p$*/i) {print "$&\n";}
else {print "No match, sorry.\n";}
}
close INPUT;

The output is supposed to be:
Perl
pattern
pattern
Perl
help

But I only get:
P
p
p
P
p

How do I make the program print out the whole word?
Three answers:
jake cigarâ„¢ is retired
2007-03-13 10:57:35 UTC
if you broke them into words...



if ($word =~ /^p/i) {print "$word\n";}

if ($word =~ /p$/i) {print "$word\n";}



but as lines ....



if ($line =~ m/\b\w*p\b/i) {print "$&\n";}

if ($line =~ m/\bp\w+\b/i) {print "$&\n";}





that looks about right!
injanier
2007-03-13 12:31:56 UTC
in \b\^p*\bi:

the ^p is redundant; \bp gets a p at the beginning of the word. p* gets any number of p's; what you really want is p.*, that is, p followed by whatever. You'll want to make that non-greedy, so p.*?. Finally, the if statement will only get the first instance in the line; you need a loop to get them all.

p$ matches a p at the end of the string, but none of what comes before it; not what you want.

So, try this instead:

while($line =~ m/\bp.*?\b/ig) {print "$&\n";}

while ($line =~ m/\w*p\b/ig) {print "$&\n";}
corkern
2016-12-02 03:42:01 UTC
you would more beneficial useful layout intently your database and save all separate fields in diverse columns, including value. Then among different options you'll retrieve out of your database also the price information. this manner it will be more beneficial accessible to get and replace the options (phpmyadmin and different procedures are available for viewing and manipulating mysql). undemanding queries (replace) will then show you how to honestly replace the costs from a form. you would more beneficial useful save information aspect faraway from own homestead web page because it will be complicated to replace.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...