Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl pattern match variable question

I'm trying to open a file, match a particular line, and then wrap HTML tags around that line. Seems terribly simple but apparently I'm missing something and don't understand the Perl matched pattern variables correctly.

I'm matching the line with this:

$line =~ m/(Number of items:.*)/i;

Which puts the entire line into $1. I try to then print out my new line like this:

print "<p>" . $1 . "<\/p>;

I expect it to print this:

<p>Number of items: 22</p>

However, I'm actually getting this:

</p>umber of items: 22

I've tried all kinds of variations - printing each bit on a separate line, setting $1 to a new variable, using $+ and $&, etc. and I always get the same result.

What am I missing?

like image 211
jeff Avatar asked Jan 26 '26 02:01

jeff


1 Answers

You have an \r in your match, which when printed results in the malformed output.

edit: To explain further, chances are your file has windows style \r\n line endings. chomp won't remove the \r, which will then get slurped into your greedy match, and results in the unpleasant output (\r means go back to the start of the line and continue printing).

You can remove the \r by adding something like

$line =~ tr/\015//d;
like image 121
ivancho Avatar answered Jan 28 '26 18:01

ivancho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!