in reply to bash script to perl script
To do it perfectly you should learn perl and port your bash script: