http://qs1969.pair.com?node_id=496428

gasho has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to come up with universal code :) that will extract value between $StartTag value $EndTag from single line. I am having problem when special characters are involved.
my $line = <DATA>; my @wanted_substrings=(); #No Problem #my $StartTag='START'; #my $EndTag='END'; #Error Unmatched ) in regex; marked by <-- HERE in m/TRicky\(.*?) #my $StartTag="TRicky\\"; #my $EndTag="\\endTricky"; #No Error but no value VALUE #my $StartTag="Next\$"; #my $EndTag="\^Next"; #No Error but no value VALUE my $StartTag="Last\+"; my $EndTag="\+some"; if ($line=~/$StartTag(.*?)$EndTag/g) { push(@wanted_substrings,$1) ; } print join "\n", @wanted_substrings; __DATA__ CharSTARTanotherENDCharTRicky\VALUEE\endTrickyNext$VALUE^NextLast+VALU +E+some
#Forgot to mention if I do not use $StartTag or $EndTag # and insted use actual string that it will work. #Instead if ($line=~/$StartTag(.*?)$EndTag/g) #This one works if ($line=~/TRicky\\(.*?)\\endTricky/g) #Problem is that I have to use varialble $ because #I am using it as an arg in my sub sub getInfoFromSingleLineMultiLineFile { #$stag,$etag uses as arguments my ($InputFile,$stag,$etag)=@_; my ($line,@wanted_substrings); #Openning file for reading open(IFH,"$InputFile") || die "Can't open file: $InputFile\n"; while($line=<IFH>) { if ($line =~ m/$stag(.*?)$etag/g) { push(@wanted_substrings,$1); } } return @wanted_substrings; }
Thanks in advance Gasho