You can just use Perl for the whole script instead of Bash.