saurabh.hirani has asked for the wisdom of the Perl Monks concerning the following question:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Returning string and numerical data types from subroutines
by ikegami (Patriarch) on May 15, 2009 at 17:03 UTC | |
|
Re: Returning string and numerical data types from subroutines
by mikeraz (Friar) on May 15, 2009 at 18:18 UTC | |
|
Re: Returning string and numerical data types from subroutines
by gwadej (Chaplain) on May 15, 2009 at 16:53 UTC | |
|
Re: Returning string and numerical data types from subroutines
by afoken (Chancellor) on May 15, 2009 at 20:36 UTC | |
by saurabh.hirani (Beadle) on May 16, 2009 at 05:27 UTC | |
|
Re: Returning string and numerical data types from subroutines
by Fletch (Bishop) on May 15, 2009 at 16:27 UTC | |
by Anonymous Monk on May 15, 2009 at 16:35 UTC | |
|
Re: Returning string and numerical data types from subroutines
by John M. Dlugosz (Monsignor) on May 15, 2009 at 20:30 UTC |