Why is my replacement empty?

I am trying to put the material in parentheses in the value of the src attribute in the img tag:

while(<TOCFILE>) { $toc_line = $_; $toc_line =~ s/<inlineFig.*?(\.\.\/pics\/ch09_inline99_*?\.jpg)*?<\/inlineFig>/<img src="${1}" alt="" \/\>/g; $new_toc_file .= $toc_line; } 

Therefore, I expected to see tags like this in the output:

 <img src="../pics/ch09_inline99_00" alt="" /> 

But instead, I get:

 <img src="" alt="" /> 
+3
source share
3 answers

There is an error in your regex so the phrase will never match:

 inline99_*?\.jpg ^^^ 

I think you forgot \d in front of the star, judging by the example data that you are trying to match.

You don’t even ask it to match when you put *? after the captured group. So it doesn’t mean anything. So what you get: nothing.

Besides:

 ($PATTERN)*? 

will only display the last that matches. This is probably not what you want either. For instance:

 $_ = 'one two three'; s/(\w+\s*)*/$1/; print; 

prints three.

+12
source

1) could use some examples of what you are analyzing.

2) if you use "x" at the end of the expression, you can put white space and comments in the regular expression to make it more understandable

3) In addition, breaking it, you will notice that in the second part of the content inside () there was no coincidence of numbers ... instead of looking for 0 or more '_' and breaking when it saw numbers, therefore it did not match.

 while(<TOCFILE>) { $toc_line = $_; $toc_line =~ s/ # replace the follwoing <inlineFig # match this text .*? # then any characters until the next sequence matches ( # throw the match into $1 \.\.\/pics\/ch09_inline99_ # ..\pics\cho9_inline99_ \d*?\.jpg # folowed by 0 or more numbers )*? # keeping doing that until the next sequence matches <\/inlineFig> # match this text / # with the follwoing <img src="${1}" alt="" \/\> # some text and the result of $1 above. /xg; # <- the x makes it ignore whitespace and #comments $new_toc_file .= $toc_line; } 

4), as already mentioned, () *? returns only the last match at $ 1, but this should not be a problem if your input will be only of a certain format.

+3
source

Correct your template, as suggested by bart, and consider using the variable "topic" $ _ instead of explicitly assigning the data read from the file descriptor to another variable.

 #!/usr/bin/perl use warnings; use strict; my $new_toc_file; { # localizing $_ protects any existing value in the global $_ # you should localize $_ even if you choose to assign it to a variable local $_; while(<DATA>) { # in the absence of the bind operator =~, s/// operates against $_ s!<inlineFig.*?(\.\./pics/ch09_inline99_.*?\.jpg)</inlineFig>!<img src="$1" alt="" />!g; $new_toc_file .= $_; } } print $new_toc_file, "\n"; __END__ <inlineFig>../pics/ch09_inline99_00.jpg</inlineFig> 
+1
source

All Articles