开发者

How can I output a die() message without the location information?

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开发者_StackOverflow

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.


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.


I have a chapter on "Error Handling" in Mastering Perl that discusses this. Although you can eliminate file and line number merely by 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 not to 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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜