< Day Day Up > |
Hack 47. Bring the Google Calculator to the Command LinePerform feats of calculation on the command line, powered by the magic of the Google calculator. Everyone, whether they admit it or not, forgets how to use the Unix dc command-line calculator a few moments after they figure it out for the nth time and stumble through the calculation at hand. And, let's face it, the default desktop (and I mean computer desktop) calculator usually doesn't go beyond the basics: add, subtract, multiply, and divide—you'll have some grouping ability with clever use of M+, M-, and MR, if you're lucky. What if you're interested in more than simple math? I've lived in the U.S. for years now and still don't know a yard from three feet (I know now, thanks to the Google Calculator), let alone converting ounces to grams or stone to kilograms. This two-line PHP script by Adam Trachtenberg (http://www.trachtenberg.com) brings the Google calculator to your command line so that you don't have to skip a beat—or open your browser—when you just need to calculate something quickly. 2.29.1. The CodeThe script uses PHP (http://www.php.net), better known as a web programming and templating language, on the command line, passing your calculation query to Google, scraping the returned results, and dropping the answer into your virtual lap.
#!/usr/bin/php <?php preg_match_all('{<b>.+= (.+?)</b>}', file_get_contents('http://www.google.com/search?q=' . urlencode(join(' ', array_splice($argv, 1)))), $matches); print str_replace('<font size=-2> </font>', ',', "{$matches[1][0]}\n"); ?> Save the code to a file called calc in your path (I keep such things in a bin in my home directory) and make it available to run by typing chmod +x calc. 2.29.2. Running the HackInvoke your new calculator on the command line ["How to Run the Scripts" in the Preface] by typing calc (or ./calc if you're in the same directory and don't feel like fiddling about with paths) followed by any Google calculator query that you might run through the regular Google web search interface. Here are a few examples: % calc "21 * 2" 42 % calc 26 ounces + 1 pint in ounces 42 US fluid ounces % calc pi 3.14159265 % calc answer to life, the universe and everything 42 If your shell gives you a parse error or returns garbage, try placing the calculation inside quotation marks. For example, calc 21 * 2, without the double-quotes in the previous example, returns $int($<b>calc.
|
< Day Day Up > |