Thursday, January 05, 2006

The Return of the Value

Okay, so the only way to return a value from a function is with a side effect. What the heck do you do to return values?

One option is to have the function create real output and capture it.
#!/bin/bash

date_diff() {
t2=$(date -d "$1" +%s)
t1=$(date -d "$2" +%s)
echo $((t1-t2))
}

secs=$(date_diff "Dec 25" "now")
echo "$secs more shopping seconds until Christmas"
This works, but costs the execution of a subshell each time you call the function. A more efficient approach is to capture output in a global, and use a naming convention to keep from accidentally stepping on a some other variable with the same name.

I've seen a handful, but I like this:
date_diff() {
t2=$(date -d "$1" +%s)
t1=$(date -d "$2" +%s)
_date_diff=$((t1-t2))
}

date_diff
echo "$_date_diff more shopping seconds until Christmas"
Try using the name of the function, preceded by an underscore, to hold the return value of the latest call.

0 Comments:

Post a Comment

<< Home