Perl内置于exit并在一个命令中打印

Bry*_*eld 14 perl exit die

我知道我可以死,但打印出脚本名称和行号.

我喜欢做类似的事情 die 'error' if $problem;

有没有办法在不打印行号的情况下这样做?

不必使用牙箍会很好 if($problem){print 'error';exit}

run*_*rig 23

die错误消息中添加换行符会抑制添加的行号/ scriptname verbage:

die "Error\n"
Run Code Online (Sandbox Code Playgroud)


Eri*_*rom 19

您可以在die字符串中添加一个新行,以防止perl添加行号和文件名:

die "oh no!\n" if condition;
Run Code Online (Sandbox Code Playgroud)

或者写一个函数:

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

bail_out 'oh no!' if condition;
Run Code Online (Sandbox Code Playgroud)

还要记住,默认为stdout时die打印到stderr print.


Dav*_*ous 12

你可以使用相当自然的声音:

print "I'm going to exit now!\n" and exit if $condition;
Run Code Online (Sandbox Code Playgroud)

如果您有perl 5.10或更高版本并添加use 5.010;到脚本的顶部,您也可以使用say,以避免必须自己添加换行符:

say "I'm going to exit now!" and exit if $condition;
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果打印失败,程序将不会退出.最好说"print(...),退出if条件;". (2认同)