Reputation:
I want to replace existing print STDERR
statements in my codebase.
Apparently, I find them not very suitable to eyes, or is it just me. Should I be using warn
knowing that It will be caught by $SIG{_WARN_}
handler. Or is there any better option. And if yes, why use those options and not print STDERR
.
Upvotes: 1
Views: 518
Reputation: 46187
Creating a debug
subroutine to wrap print STDERR
would give you a lot of flexibility above and beyond what simple print
or warn
statements provide, such as the ability to turn debugging messages off or redirect them to different destinations. For example, just off the top of my head:
sub debug {
my ($msg, %param) = @_;
$param{level} //= 1; # default if no level specified
return if $param{level} < $config{log_level};
given ($param{dest}) {
when ('mail') { send_email_to_admin(subject => "Application Error!", body => $msg) }
when ('log') { write_to_logfile($msg) }
default { print STDERR $msg }
}
}
debug('foo'); # goes to STDERR by default
$config{log_level} = 2;
debug('bar'); # message is ignored as unimportant at current logging level
debug('bar', level => 3, dest => mail); # still important; gets emailed to admin
Upvotes: 1
Reputation: 57590
The benefit of print STDERR
is that you can see at once what will happen—you print something to STDERR. This may be a debug message, or something.
The warn
function is slightly different:
You should probably use this for warnings, not for logging data
You might be also interested in the Carp
family of functions. carp
works like warn
, but reports the line number/file from the point of call. cluck
will warn
with a stack trace.
But nothing prevents you from rolling your own. A functionally equivalent sub to print STDERR
would be:
sub debug { print STDERR @_ }
You can now literally s/print STDERR/debug/g
your source, except for that one occurence. Also, you will have to declare or import that debug
function before you use it if you want to be able to leave out the parens around the arguments.
debug "this ", "is ", "DATA";
Point to consider: calling a sub is slooow, whereas print
is a built-in opcode. You can trade beauty for performance, and vice versa.
Upvotes: 2