Hack 11. Run Perl from Emacs


Make Perl and Elisp play nicely together.

Emacs's long and varied history happens to embody much of Perl's "There's More Than One Way To Do It" approach to things. This is especially evident when you run a small bit of Perl code from within Emacs. Here's how to do just that.

The Hack

Suppose you really need to know the higher bits of the current value of time( ). In Perl, that's print time() 8>>;. You could use the shell-command command (normally on Control-Alt-One), and enter:

perl -e 'print time( ) >> 8;'

Emacs will dutifully run that command line and then show the output. Note though that you have to remember to quote and/or backslash-escape the Perl expression according to the rules of your default shell. This quickly becomes maddening if the expression itself contains quotes and/or backslashes or even is several lines long.

An alternative is to start an "Emacs shell" in an Emacs subwindow, then start the Perl debugger in that shell. That is, type alt-x " shell " Enter, and then perl -de1 Enter, and then enter the expression just as if you were running the debugger in a normal terminal window:

% perl -de1 Loading DB routines from perl5db.pl version 1.27 Editor support available. Enter h or \Qh h' for help, or \Qman perldebug' for more help. main::(-e:1):    1   DB<1> p time( ) >> 8 4448317   DB<2>

This means you don't have to escape the Perl expression as you would if you were sending it through a command line, but it does require you to know at least a bit about the Perl debugger and the Emacs shell. It also becomes troublesome in its own way when your expression is several lines long.

A simpler alternative is to save your snippet to a file named delme123.pl and to run that via a command line, but this is a very effective way to fill every directory in reach with files named with the same variant of delme.

I prefer defining a new function just for running Perl code in the Region (what you have selected in Emacs, between the Point and the Mark):

(defun perl-eval (beg end)   "Run selected region as Perl code"   (interactive "r")   (shell-command-on-region beg end "perl")    ; feeds the region to perl on STDIN )

I bind it to my CTRL-Alt-p key:

(global-set-key "\\M-\\C-p" 'perl-eval)

Then when I want to run some Perl expression in whatever buffer I happen to be in, I just set the mark, type the expression, and hit CTRL-Alt-p. It requires no special escaping, nor are there any problems when the Perl code spans several lines.



Perl Hacks
Perl Hacks: Tips & Tools for Programming, Debugging, and Surviving
ISBN: 0596526741
EAN: 2147483647
Year: 2004
Pages: 141

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net