Can anyone please explain me about carp
subroutine with sample Perl code?
views:
171answers:
2
+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
2010-04-02 04:32:59
Stack trace: http://en.wikipedia.org/wiki/Stack_trace -- the list of functions that you are currently inside of
mobrule
2010-04-02 05:04:10
Nice explanation!!! Thank you so much!!!
2010-04-02 05:13:24
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
2010-04-02 10:56:54
Welcome to the 10k club. :)
brian d foy
2010-04-02 16:18:41
Woo hoo! Thanks bdf.
mobrule
2010-04-02 17:40:00