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:
What is captured within $1 if used with alternation?

 



Cupidvogel
Novice

May 4, 2012, 8:13 AM

Post #1 of 3 (649 views)
What is captured within $1 if used with alternation? Can't Post

Hi, if I use something like this:


Code
"I love fred and barney" =~ /(barney|fred)/ ? print "$1\n" : print "No.\n";


it prints out fred. It suggests that the regex engine starts scanning the string from left to right searching whether any pattern on either side of the alternation matches it, and if it does, then that is stored inside $1 and the process ends.

But if I run something like this:


Code
"I love fredder and fred" =~ /(fred|fredder)/ ? print "$1\n" : print "No.\n";


prints out fred. Surely while scanning from left, fredder comes first, so that should be stored in $1, but it is not. Not only that, whatever configuration be the strings fred and fredder in the regex and string, i.e fredder and fred and (fred|fredder), fred and fredder and (fred|fredder), fredder and fred and (fredder|fred), fred and fredder and (fredder|fred), it always outputs fred. Can anyone explain what is going on?


BillKSmith
Veteran

May 4, 2012, 8:44 AM

Post #2 of 3 (639 views)
Re: [Cupidvogel] What is captured within $1 if used with alternation? [In reply to] Can't Post

Your guess about how the matching engine works is correct. Note that in your second case, the pattern /fred/ matches whichever comes first, the word 'fred' or the first four characters of 'fredder'. In either case, it returns the string 'fred' in $1.
Good Luck,
Bill


Cupidvogel
Novice

May 4, 2012, 8:47 AM

Post #3 of 3 (637 views)
Re: [BillKSmith] What is captured within $1 if used with alternation? [In reply to] Can't Post

Yeah right. Thanks!

 
 


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

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