This is an example where you should rewrite the entire shell script in Perl.
Agreed.
After being scarred by having to maintain an ugly 5000-line shell script (that started life as
a quick ten line script) I put forward a case that Perl
should almost always be preferred to Unix shell:
Unix shell versus Perl.
The key reason is that Perl can comfortably scale to much larger scripts than shell.
And shell scripts have a way of growing ... and growing ... and growing ... until they become
maintenance nightmares. But by then how do you justify a rewrite?
The cost of rewriting, the opportunity cost of not working on something else,
and the risk of breaking previously working code in the rewrite.
So write it in Perl to begin with.