5

According to the Carp module documentation, croak() should not produce any stack trace unless $Carp::Verbose evaluates to true. But for some reasone, croak() always behaves like confess() in my environment, i.e. always printing a stack trace, even when it should not..

Here is a test script:

#!/usr/bin/perl

use Modern::Perl;
use Carp;

sub func
{
    say "Carp::Verbose = $Carp::Verbose";
    croak "There should be no stack trace after this message!";
}

sub main
{
    func();
}

main;

And here is the result it produces on my system:

$ ./croak
Carp::Verbose = 0
There should be no stack trace after this message! at ./croak line 8
    main::func() called at ./croak line 13
    main::main() called at ./croak line 16

Maybe someone has encountered this issue or has any clue about the root cause?

Here is some info about my environment:

Ubuntu 12.04 LTS
Linux 3.2.0-27-generic x86_64
perl 5, version 14, subversion 2 (v5.14.2) built for x86_64-linux-gnu-thread-multi

Also I get the same wrong behavior on my SL6 system:

Scientific Linux SL release 6.3 (Carbon)
kernel-2.6.32-279.1.1.el6.x86_64
perl, v5.10.1 (*) built for x86_64-linux-thread-multi
Dima Chumak
  • 139
  • 1
  • 4

2 Answers2

5

One of Carp's rules for which frame of the stack trace to use for the error message is:

  1. Any call from a package to itself is safe.

Since your code doesn't use any packages other than main, and since another rule is that the Carp package itself is safe, Carp can't decide what line of code to use for its error message, so it punts and prints out the whole stack trace.

Oh, it's actually there in the Carp perldoc:

What they do is search the call-stack for a function call stack where thay have not been told that there shouldn't be an error. If every call is marked safe, they give up and give a full stack backtrace instead.

This line in the Carp::short_error_loc function is your smoking gun:

return 0 unless defined($caller);    # What happened?
mob
  • 117,087
  • 18
  • 149
  • 283
  • I've found the following answer to question about [Carp vs warn/die](http://stackoverflow.com/a/188846/1559353), indeed Damian Conway recommends to use `carp` over `warn` in his PBP book. So I'm wondering is this a good practice to use `warn/die` in `main` package (i.e. in script) and use `carp/croak` only in modules? – Dima Chumak Aug 10 '12 at 11:21
  • @DimaChumak: yes, you should use `warn / die` in scripts, and `carp/croak` in modules. – Medlock Perlman Aug 04 '16 at 15:11
3

Half an answer: it has something to do with the code being all in the same package. If you call the entry point from a different package, croak works as you expect.

daxim
  • 39,270
  • 4
  • 65
  • 132