700 Software
700 Software

Reputation: 87773

Perl built in exit and print in one command

I know I can die but that prints out the script name and line number.

I like to do things like die 'error' if $problem;

Is there a way to do that without printing line number stuff?

It would be nice not to have to use braces if($problem){print 'error';exit}

Upvotes: 15

Views: 9414

Answers (5)

dolmen
dolmen

Reputation: 8696

Here is an answer to the question you completed in you comment to Eric.

To do both (print STDOUT and print without line number) you can still use die by changing the __DIE__ handler:

$SIG{__DIE__} = sub { print @_, "\n"; exit 255 };

die "error" if $problem;

Upvotes: 0

David Precious
David Precious

Reputation: 6553

You could use the fairly natural-sounding:

print "I'm going to exit now!\n" and exit if $condition;

If you have perl 5.10 or above and add e.g. use 5.010; to the top of your script, you can also use say, to avoid having to add the newline yourself:

say "I'm going to exit now!" and exit if $condition;

Upvotes: 12

shawnhcorey
shawnhcorey

Reputation: 3601

You can create complex messages with sprintf:

die sprintf( ... ) if $problem;

Upvotes: -5

Eric Strom
Eric Strom

Reputation: 40142

You can append a new line to the die string to prevent perl from adding the line number and file name:

die "oh no!\n" if condition;

Or write a function:

sub bail_out {print @_, "\n"; exit}

bail_out 'oh no!' if condition;

Also keep in mind that die prints to stderr while print defaults to stdout.

Upvotes: 20

runrig
runrig

Reputation: 6524

Adding a newline to the die error message suppresses the added line number/scriptname verbage:

die "Error\n"

Upvotes: 25

Related Questions