views:

76

answers:

3

I've got a script that throws an exception via die. When I catch the exception I want to output the message without the location information attached.

This script:

#! /usr/bin/perl -w

use strict;

eval {
    die "My error message";
};
if($@) {
    print $@;
}

outputs My error message at d:\src\test.pl line 7.

I would prefer just to get the output: My error message

Hopefully people don't focus on why I want to do it but if someone is interested then:

The way my script works, it looks for input and dispatches each piece of input to a handler, if it comes across a piece of input that it can't handle then it throws, so all the exceptions are coming from the same piece of code. Hence the location isn't terribly helpful in this situation.

+11  A: 

Add \n to your string:

die "My error message\n"

This is documented in die:

If the last element of LIST does not end in a newline, the current script line number and input line number (if any) are also printed, and a newline is supplied.

toolic
Thanks toolic. That was what I was looking for!
chollida
learn something new @ SO every day.
Erik
A: 

See the perlfunc entry for die for all the extra info. And end your message with \n.

Don
+7  A: 

I have a chapter on "Error Handling" in Mastering Perl that discusses this. Although you can eliminate file and line number merely by not ending your message with a new line, you can also die with a reference:

eval {
    time % 2 ?
        die { 
            message => q(I died!),
            level   => 'really really serious',
            }
        :
        die "I died as a string!\n";
    };

if( ref $@ ) {
    print "Reference message was $@->{message}\n";
    }
else {
    print "$@\n";
    }

I tend to not like newlines at the end of error messages, and although I haven't seen your code, it sounds like a situation where I'd want to add extra information to the exception so I can track down what's going on.

You might also consider using one of the many Exception modules on CPAN.

brian d foy
Thanks for the answer Brian. I was not aware of being able to die with a reference. I can see this being very useful.
chollida