regulatorz
asked on
Perl regular expression question help
Ok I'm new programmer to Perl and all that regular expressin stuff isn't going well with me. Basically I'm trying to understand the following 2 lines of code:
($0=~ m,(.*)/[^/]+,) && unshift (@INC, "$1");
($0=~ m,(.*)\\[^\\]+,) && unshift (@INC, "$1");
Can someone please explain what that regular expression is comparing to? Is that m there the match keyword? Isnt the format for match m//? I'm confused! What is been put in the array @INC?
($0=~ m,(.*)/[^/]+,) && unshift (@INC, "$1");
($0=~ m,(.*)\\[^\\]+,) && unshift (@INC, "$1");
Can someone please explain what that regular expression is comparing to? Is that m there the match keyword? Isnt the format for match m//? I'm confused! What is been put in the array @INC?
ASKER
Ok so for this one say if $0 has "/test/blah.pl" then $1 will have "/test" or empty?
The first expr matches /test ($1 = "/test"
and i think the second expr is used for filenames of the type \test\blah.pl
and i think the second expr is used for filenames of the type \test\blah.pl
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
some notes on regex.
once you see .* in a regex, hold on and think how you can avoid it. that is because .* can very easily cause heavy backtracking what makes your regex slow.
a better way (and a non-platform-specific one) for your code above is this:
BEGIN { use File::Basename; unshift ( @INC, (fileparse($0))[1] ); }
holli
once you see .* in a regex, hold on and think how you can avoid it. that is because .* can very easily cause heavy backtracking what makes your regex slow.
a better way (and a non-platform-specific one) for your code above is this:
BEGIN { use File::Basename; unshift ( @INC, (fileparse($0))[1] ); }
holli
ASKER
thanks for all the help.
m// is the matching operator as you know, but perl allows any kind of specifiers, for ex m, , is also a matching specifier, and also m. .
http://webdevelopment.developersnetwork.com/Articles.asp?Article=143
And for your next question, when we do matching like
m// or m,, or anything of that sort, then anything that is specified in the brackets ie () is assigned the value $1.
ie m/(.*)/ puts the value that matches (.*) into $1.
see ->
http://www.comp.leeds.ac.uk/Perl/sandtr.html