Hi guys,
I am writing a subroutine for daemonizing a process. Broadly speaking I've written it like this:
sub daemonize {
# try to daemonize
if (success) {
return 1
} else {
return errstr
}
}
I call it this way
$isdaemon = daemonize()
if ($isdaemon ne "1") {
print "error: $isdaemon";
}
The problem with this is that the caller needs to do a "ne" check as it works for both 1 and error string. I would like to change the calling interface to:
if (! daemonize) {
report error
}
But in the current implementation I can't use the desired way because if daemonize fails it returns an errstr which passes the "if (! daemonize)" test. I want to report the error, so I cannot return 0 on failure.
I wanted to set the errstr in a way that $! does it - which is make the subroutine call more intuitive, like the way we use open or close
open($fh, file) or die "$!";
The best I can do is this:
use Scalar::Util;
sub daemonize {
# try to daemonize
if (success) {
return 1
} else {
return dualvar 0, errstr
}
}
so the usage is
$isdaemon = daemonize;
if ($isdaemon == 0) {
print "error: $isdaemon";
}
which is better than the first way because I can use $isdaemon is both the string and numeric context and get my work done, but it still isn't as good as the way $! does it.
- Is there a better way?
- Can I not set $! and use my subroutines like I have used open() call above? A perl DBI module sets $DBI::err variable. I may do that but that's plan B.
- How do you guys handle such situations where in the return value is more than success or error - like a subroutine which checks if lockfile is in use or not - return 0 if lockfile free, return pid if someone using the lockfile, return error if failed to check if someone is using it?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.