user152037
user152037

Reputation: 209

How to tell the line number when `die`?

I'd like to write sth like:

die "Error in file $0 line number $line_number_of_this_cmd_in_file \n";

In my perl script file.

Any help? Thx a lot!

(perl 5)

Upvotes: 3

Views: 1098

Answers (2)

harmic
harmic

Reputation: 30577

If you do not put \n at the end of the string you pass to die, then perl will automatically add the line number.

Otherwise, the token __LINE__ will give you the current line number in your script (and __FILE__ gives the current file name).

Unless you meant the current line number of the file you just read from - that is available in $.

Upvotes: 10

DeVadder
DeVadder

Reputation: 1404

That is quite easy: Drop the \n at the end of the line and die will append whatever message you wrote with the name of the script and the line number. For example:

die "Encountered error 15 ";

will result in it printing:

"Encountered error 15 at script.pl line 42\n"

or whatever is applicable.

Upvotes: 8

Related Questions