dannyman.toldme.com


Excerpts, FreeBSD, Technical

Perl: Convert Celsius and Fahrenheit

I recently had a need for two quick temperature conversion algorithms in a Perl script. I asked Google, but did not immediately get a great answer, so here’s my answer:


# Two quick helper functions: CtoF and FtoC
sub CtoF { my $c = shift; $c =~ s/[^\d\.]//g; return (9/5)*($c+32); }
sub FtoC { my $f = shift; $f =~ s/[^\d\.]//g; return (5/9)*($f-32); }

The regex is to untaint the input datum, and could be eliminated if you know that your variable is clean. This code has been incorporated into a systems health and data trend monitoring script for FreeBSD. For the vaguely interested, here’s today’s perldoc:

check_temp($result, $command, $red, $yellow)
        Requires $results -- hashref to %results array.
        Requires $command -- unix command that prints a text representation
                             of system temperature in degree Celsius.
        Optional $red -- threshhold temperature for red alert in degrees
                         Fahrenheit.  (Default: 100)
        Optional $yellow -- threshhold temperature for yellow alert in
                            degrees Fahrenheit.  (Default: 90)

        Will populate:
                temp.C
                temp.F

        Note that input is expected in Celsius, but thresholds are
        calibrated in Fahrenheit.  This is because I am an American, and
        because I personally feel that Fahrenheit is a more inuitive
        temperature metric for humans.

        I have found that the following may work for $command:

                /sbin/sysctl -n hw.acpi.thermal.tz0.temperature
                /usr/local/bin/mbmon -T 1 -c 1

        As there is no consistent, reliable way to measure temperature, and
        because mbmon can cause your system to crash, and because different
        systems have different temperature tolerances, this check must be
        configured explicitly in lilsis.conf.

As you can guess, mbmon can be had from ports. And yes, while I love the metric system, I prefer Fahrenheit because its 0-100 metric is roughly calibrated from “colder than it gets in Denmark” to “the temperature of human blood” which is easier for my monkey brain to grasp than the freezing and boiling points of water.

Read More

Next:
Previous:
Categories: Excerpts, FreeBSD, Technical

Discover more from dannyman.toldme.com

Subscribe now to keep reading and get access to the full archive.

Continue reading