One-Liners: Simple Calculator

Ever needed to do a little math really quick, the sort of thing that's too complex to do in your head? I normally keep a calculator around for just these reasons, but my desk is really messy (one of the occupational hazards of being a writer), and I'm lucky if I can find stuff I really need. My computer, like all computers, comes with an online calculator, but because I'm often sitting working with Perl at a command line I can type faster than I can pull down a menu.

With one-liners, Perl enables your computer to become the most complicated basic calculator in the world.

% perl
						-e 'print 154/7'
22

Note

Don't forget, on Windows, use double quotes, not single quotes after the -e.


This isn't a very elegant one-liner. I left off the -w option, because we're not doing anything here that requires warnings. I also left off the double quotes on the item we're printing (the math being calculated) because they're not necessary hereā€”but it also means that there isn't a newline, so the next command prompt will show up right next to the result (you'll have to figure out what is result and what is prompt). Finally, I also left off the semicolon because there's a loophole in Perl that says that if there's only one statement in the script you don't need the semicolon. And yet, it still works. If I wanted to make this pretty and proper, it would look more like this:

% perl
						-w
						-e 'print "154/7
";'
					

This would give you roughly the same result, but it would take a lot more characters, and, therefore more opportunities to mistype. Sometimes with Perl it's just fine to be lazy and ugly (well, in your scripts, at least. Perl doesn't care about your personal habits).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.115.71