You have a few problems here that we can clear up. First, you need to use warnings. Either include -w on the shebang line of your script:
#!/usr/bin/perl -w
Or use the "warnings" pragma if your version of Perl supports it:
use warnings;
These will tell you that "$main::str" was used only once, which can help you see that you have a typo in the following line:
$str = s/.*\-D*?//;
Further, 'use strict;' will catch errors like that.
You probably meant for $str to be $_. Also, you have an equals '=' sign when you want the regex binding operator: '=~'. The reason you are getting output is because your regular expression is evaluating against the value of $_ and you are throwing away the value of $str. You can either leave off the '$str =' part, or change the code to the following:
$_ = "text1 text2 -f -DFLAG1 -global -DFLAG2 -DFLAG1";
s/.*?(?=-D)//;
print "$_\n";
The (?=-D) uses a positive lookahead. That checks to see if it matches data, but doesn't include that data in the text that is matched. See perlre for more information on this.
Also, I don't like the dot star in this regular expression. If your data is likely to always be in this format, try the following:
s/[^-]+-[^-]+//;
However, that regex looks a bit obscure. If this is not a time-sensitive script, you may want to stick with the first one. See Death to Dot Star! for information on problems with the dot star '.*' combination in regexes.
That regular expression, broken out with the /x modifier, reads like this:
s/
[^-]+ # Negated character class - match one or more
# of anything that is not a dash: "text1 text2 "
- # match the dash: "-"
[^-]+ # Negated character class - match one or more
# of anything that is not a dash: "f "
//x;
No offense, but you seem to have some troubles with English. Since this answer is a bit complicated, feel free to e-mail me at poec@yahoo.com if you have any questions.
Cheers,
Ovid
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats. |