There are some problems with the code you pasted. It will not compile as there is a missing } somewhere, as you did not indent the while block it is not clear where it should be but I guess before &heading. Which brings us to problem two you call &heading but there is no sub heading, you probably want to rename heading2 to heading. A couple of other minor points you probably want $ARGV instead of @ARGV. It is also more common to use heading() instead of &heading.
As for what your code is doing and whether or not it is the best approach, I agree with GotToBTru. It would help if you provided an example of the input data and an example of the desired output.