While answering this SO question, I ran into a debug misery. It took me an embarrassing amount of time and experiments to understand why.

Here's a simplified version of the problem. Can you spot the issue?

$ cat ip.txt
a b c d
i j k l

# Change only first two occurrences of spaces with tabs
$ perl -pe '$c=2; s/ /\t/ while $c--' ip.txt
a       b       c d
i       j       k l

# Wanted to generalize the solution to match one-or-more whitespaces
# But it doesn't work!!!
$ perl -pe '$c=2; s/\s+/\t/ while $c--' ip.txt
a       b c d
i       j k l

Click to view answer The substitution works from start of the line for every iteration of the while loop. Tab is one of the whitespace characters, so after the first substitution, the tab gets matched for rest of the iterations.