tags:

views:

171

answers:

2

Can anyone please explain me about carp subroutine with sample Perl code?

+2  A: 

http://perldoc.perl.org/Carp.html

pst
+11  A: 

See the perldoc for Carp.

carp is a alternative for Perl's warn function that uses stack trace information to show you where you called a function that issued a warning. This can be more helpful than warn's behavior of telling you where the warning occurred.

An example:

This program:

1: sub square_root {
2:  my $arg = shift;
3:  if ($arg < 0) {
4:    warn "Can't take square root of a negative number";
5:  } else {
6:    return sqrt($arg);
7:  }
8: }
9: print square_root(-4);

tells you:

Can't take square root of a negative number at carpdemo.pl line 4.

But if we change warn to carp:

1: use Carp;
2: sub square_root {
3:  my $arg = shift;
4:  if ($arg < 0) {
5:    carp "Can't take square root of a negative number";
6:  } else {
7:    return sqrt($arg);
8:  }
9: }
10: print square_root(-4);

it tells you:

Can't take square root of a negative number at carpdemo.pl line 4
        main::square_root(-4) called at carpdemo.pl line 10

The extra line of information is helpful in tracking down places where you might be using a function or module incorrectly.

mobrule
Stack trace: http://en.wikipedia.org/wiki/Stack_trace -- the list of functions that you are currently inside of
mobrule
Nice explanation!!! Thank you so much!!!
From http://dictionary.reference.com/browse/carp : **Carp** : *to find fault or complain querulously or unreasonably; be niggling in criticizing; cavil: to carp at minor errors.*
Zaid
Welcome to the 10k club. :)
brian d foy
Woo hoo! Thanks bdf.
mobrule