What's the difference between Carp/Croak, Cluck/Confess, and verbose options?

29,951

The problem with your example is that all your subs are in the same package (the default package: main). That's not the use case that Carp was designed for.

Carp is intended to be used in modules. The reason is that when a module encounters a problem, it's often because the module's caller passed it bad data. Therefore, instead of reporting the line where the module discovered the problem, it's usually more useful to report the line where the module was called (from code outside the module). That's what the functions exported by Carp do.

There are 2 sets of yes/no options. The function can be fatal (like die) or nonfatal (like warn). It can report just the line where the function was called, or it can report a full backtrace.

         Fatal  Backtrace
carp       N        N
cluck      N        Y
croak      Y        N
confess    Y        Y

The verbose option forces backtraces on. That is, it makes carp act like cluck, and croak act like confess. You can use that when you realize that you need more debugging information, but don't want to change the code to use confess.

Share:
29,951
SineSwiper
Author by

SineSwiper

Updated on July 08, 2022

Comments

  • SineSwiper
    SineSwiper almost 2 years

    I haven't used Carp all that much because I've generally rolled my own. However, in the spirit of keeping with Core modules, I'm using it now. However, it seems like it's barely better than warn/die.

    Furthermore, what does cluck/confess/verbose even do? I've ran this short script to get an idea of the output looks like (because the Carp docs don't do it). It looks exactly the same on any run (besides the random strings).

      #!/usr/bin/perl
    
      package Warning;
    
      sub warning {
        warn "warn";
      }
    
      package CWarn;
      use Carp qw(carp cluck);
    
      sub cwarn {
        int(rand(2)) ? carp "carp" : cluck "cluck";
      }
    
      package Fatal;
      use Carp qw(confess croak);
    
      sub fatal {
        int(rand(2)) ? confess "confess" : croak "croak";
      }
    
      package Loop;
    
      use v5.10;
    
      sub loop {
        say '=' x 80;
        Warning::warning();
        CWarn::cwarn();
        loop() unless ($c++ > 10);
        Fatal::fatal();
      }
    
      package main;
    
      Warning::warning();
      CWarn::cwarn();
      Loop::loop();
    

    UPDATE: Updated the script with package names and it does make a difference. However, Carp still seems to be very basic in terms of logging information, and it doesn't support web output. I guess I'll look at other ones like CGI::Carp, Log::Output, and Log::Log4Perl.