Forum Moderators: coopster & phranque

Message Too Old, No Replies

Rookie needs help with parsing a string

PERL pattern matching

         

pmohan02

7:58 pm on Mar 15, 2004 (gmt 0)

10+ Year Member



Hi, I am relatively new to Perl and so I am having a little trouble getting a grasp of Regex and parsing a string.

This is what I am trying to do: I get the URL of the current page using the DOCUMENT_URI Environment variable, which reads: /product/100.htm. I want to pass the product number, 100, to another page. So I want to parse that variable out of that ENV variable string.

Any help would be greatly appreciated as searching for an answer with google is becoming quite a task on my eyes.

pmohan02

9:00 pm on Mar 15, 2004 (gmt 0)

10+ Year Member


I was able to get the information that I need using the following code:

$goo=$ENV{REQUEST_URI};
if ($goo =~m/product\W/){
$goo = $';
if( $goo =~m/\W/){ $goo = $`; }
}

It works, but something tells me there is an easier, quicker way to do it. Any suggestions?

coopster

10:11 pm on Mar 15, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, pmohan02!

$ENV{REQUEST_URI} =~ /([^\/]+)\.htm/; 
my $goo = $1;

This says, find anything preceding ".htm" that is not a slash symbol. Since the slash symbol itself is a special character, it has to be escaped first with a backslash (the same goes for the period in front of "htm"). The caret symbol (^) negates the character class (the "stuff" inside the brackets []). The parentheses around the match pattern says to "return this part" in Perl's specially numbered variables, $1 for the first set of parentheses encountered, $2 for the second (if we had set a second set), etc.

pmohan02

2:52 pm on Mar 16, 2004 (gmt 0)

10+ Year Member



OK, works nice. Thanks for the good explanation, I think I may actually understand.

If only this example was in some Perl site on pattern matching.

timster

6:52 pm on Mar 16, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If only this example was in some Perl site on pattern matching.

You may have more fun with pattern matching if you also search for "regular expressions," "regex," or "grep."

Perl and regular expressions often go hand-in-hand, but regular expressions really are their own language tucked inside Perl.