in reply to Re: Insert into string
in thread Insert into string
Both points are probably valid even if you're not the original poster. Not to be nasty but if it's a solution you demand then I am happy to help point out errors.
I'm going to guess that it's placing $new_tag at the end of the entire $src string (by the way, make sure you replace $strFile with $src). That's because quantifiers are "greedy" by default. They'll grab the most characters they can and still make a match. You can force a quantifier to be "lazy" by following it with a question mark. Example:
$_ = 'ab abc abcd abcde'; /a.*b/; # $& = 'ab abc abcd ab' /a.*?b/; # $& = 'ab'
Also, your options in your match and substitution are unneseccary and may cause strange results. The i is valid because HTML is case insensitive (and once the match is made, we know it's the right case, why the i in the s///?). The g is pointless because you're only making a single match. The m is also pointless because you don't use ^ or $ in your pattern. Even if you did, it may cause an unwanted effect because HTML can have random newlines. Also be careful because . will not match newlines. I like Samy_rio's answer because it addresses the latter while fixing your original problem. However, you could make the * lazy instead (and use a different pattern in addition). The space before the (.*) will also need to match a literal space character, so if you had a blank <record> tag, it wouldn't match (this may be desired behavior, but just in case).
The if line is also superflous, as the first field in the s/// is essentially a match. You have a number of options now. You should, of course, only use one line, not all of them that I list.
If you don't need to match newlines, the first will be okay (assuming you wouldn't insert a line break in the middle of a tag, but it's not unheard of). The second is a bit cumbersome and may be missing some valid characters, and the final should work in all cases. As a note, the last one shouldn't need a ? because it won't match a > as part of the character class so it shouldn't go beyond the scope of the single tag.$src =~ s/<record.*?>/$&$new_tag/; # No newlines matched $src =~ s/<record[\w\s\n-="%]*?>/$&$new_tag/; # All-inclusive class? $src =~ s/<record[^>]*>/$&$new_tag/; # Probably best
I'm going to take a guess and say that perhaps part (or all) of this code was copied and pasted from other sources or grabbed directly from a book. If not, I apologize for the accusation, but if so, try reading up on the code you are using. The mismatched variable names are one clue, and the random inclusion of /igm where the g and m are useless is another. Once again, I'm not trying to be mean or nasty, but haphazardly throwing code from other sources together can cause big problems.
Update: Fixed some spelling and code formatting
|
|---|