I was working with certificates quite often and needed something similar. That's why I build https://github.com/pete911/certinfo. Among other things, it allows you to do what the above perl script does as well:
certinfo -chains -pem-only <host>:443 > tmp_certs.pem
certinfo -no-duplicate -pem-only tmp_certs.pem > certs.pem