So, I was editing a markdown file in Vim and I wanted to convert some lines to links. The regexp pattern ended up needing non-greedy quantifier, but it didn't work. I thought I got Vim's rather weird \{-} syntax wrong and switched to using Perl from the command line instead of checking the documentation if I had actually made that mistake.

Turns out I made other mistakes in the regexp, but I didn't want to switch back to Vim. I was still scratching my head though, since I wasn't getting the expected output. Thankfully, compared to the previous debug misery, I was able to guess this issue soon enough.

Here's a simplified issue, how I debugged it and the corrected usage:

# sample input
$ cat ip.txt 
* blah blah 12 xyz 34 abcd 56 foobaz
- blah 100 apple 200 fig

# where I got stuck
# what happened to $1 and $2?
$ perl -lpe 's/^(. )(.*?\d+) (.+)/$1[$2](#$3)/' ip.txt
(#xyz 34 abcd 56 foobaz)
(#apple 200 fig)

# what I did to debug
# step 1: only $1 in the replacement
$ perl -lpe 's/^(. )(.*?\d+) (.+)/$1/' ip.txt
* 
- 
# step 2: $1 and $2 in the replacement
# only empty lines as output - bingo!
$ perl -lpe 's/^(. )(.*?\d+) (.+)/$1[$2]/' ip.txt


# $1[$2] treated as array syntax in Perl
# so, need to escape [ since array isn't intended here
$ perl -lpe 's/^(. )(.*?\d+) (.+)/$1\[$2](#$3)/' ip.txt
* [blah blah 12](#xyz 34 abcd 56 foobaz)
- [blah 100](#apple 200 fig)