in reply to how to trap errors?

See the documentation for eval.

eval { ## code that may throw errors }; if( $@ ) { ## Handle errors }