People keep giving me examples with carp instead of warn. Why? What makes carp better than warn?
For a shorter message you can use carp() or croak() which report the error as being from where your module was called. shortmess() returns the contents of this error message. There is no guarantee that that is where the error was, but it is a good educated guess.
You use croak when it's something your caller isn't doing right. die "error: $!" indicates the error is on the line where the error occured. croak "error: $!" indicates the error is on the line where the caller called your code.
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.
I use warn
for scripts and simple programs, and Carp
inside any modules. The Carp
subroutines use the filename and line number where your current subroutine was called so it's easier to find who's causing the problem (not just where the problem manifested itself).
Damian recommends Carp
instead of warn
in "Reporting Failure" in Perl Best Practices, but doesn't make the distinction between scripts as top-level code constructs and modules as components that programs use.
I've mostly not cared about that lately because I've been using Log::Log4perl to handle all of that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With