CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Odd Grep/Regular Expression issue

 



Mindsword
New User


Aug 19, 2014, 1:11 AM

Post #1 of 3 (397 views)
Odd Grep/Regular Expression issue Can't Post

I ran through the FAQs and as many places as I could before posting here. Sorry if I missed the answer.

I am currently building a large data set. Each value in the array I built contains several paragraphs of information. I set out to build a regular expression that would search each value in the array and return it if the proper keyword was found. They keyword was requested when you run the program.

I believe that's where the problem lies. Ignoring as much data as I feel I can (the array is huge), to search for the data, I have the code

Code
#@charm is the array the information is stored in. 

say "What is the keyword that we must search for?";
my $keyword = <ARGV>;

use Data::Dumper;
my @selected = grep (/$keyword/, @charm);
print Dumper @selected;
exit;


Okay. When I first ran this, it seemed to work wonderfully and I left it alone. However, when I tried to run it on a different keyword that I knew was there, it couldn't do it. I ran more tests and I realized the regular expression is looking at the last characters of each new line in the string, aka the paragraphs.

Example. If the array value looked like this:
"Mary had a little lamb
whose fleece was white as snow.
And everywhere she went
People would say hello lamb."
and I searched for lamb I would get this value once as lamb showed up at the end of the first line. If I instead searched for everywhere, this value wouldn't appear.

I assume this is because grep runs a regular expression search and $ is a variable that indicates the end of a line.

I don't know how to get around this problem. Thoughts?
Est Sularus oth Mithas

Just learning coding. 24 years old, working on learning CS for my graduate program.


BillKSmith
Veteran

Aug 19, 2014, 5:17 AM

Post #2 of 3 (393 views)
Re: [Mindsword] Odd Grep/Regular Expression issue [In reply to] Can't Post

Your main problem is that you leave a newline on the end of your keyword. Use chomp.

Code
my $keyword = <ARGV>; 
chomp $keyword;

Good Luck,
Bill


Mindsword
New User


Aug 19, 2014, 11:13 AM

Post #3 of 3 (371 views)
Re: [BillKSmith] Odd Grep/Regular Expression issue [In reply to] Can't Post

...

Wow I feel like an idiot. That makes perfect sense.

Yeah, after chomping $keyword it works wonderfully. Thank you very much.
Est Sularus oth Mithas

Just learning coding. 24 years old, working on learning CS for my graduate program.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives