perlmodulecarp

Why should I use Carp instead of warn in Perl?


People keep giving me examples with carp instead of warn. Why? What makes carp better than warn?


Solution

  • carp gives you more info as to where the message comes from (context)

    #!/usr/bin/perl
    
    use Carp;
    
    foo();
    bar();
    baz();
    
    sub foo {
      warn "foo";
    }
    
    sub bar {
      carp "bar";
    }
    
    sub baz {
      foo();
      bar(); 
    }
    

    produces

    foo at ./foo.pl line 9.
    bar at ./foo.pl line 13
            main::bar() called at ./foo.pl line 6
    foo at ./foo.pl line 10.
    bar at ./foo.pl line 14
            main::bar() called at ./foo.pl line 19
            main::baz() called at ./foo.pl line 7
    

    kinda silly for this small program but comes in handy when you want to know who called the method that's carp'ing.