perlemacs

How can I run a Perl script from Emacs?


I'm learning how to use Perl in Emacs. I used to run R with R-Studio.

How do I execute a command without leaving Emacs?

Example: In R-studio I type

    print("hello world") 

and press Ctrl+Enter and R-studio executes the command and prints "hello world". How do I do the same in Emacs for a Perl command?

I usually type Ctrl+X Ctrl+F test.pl

    print "hello world";

and then I don't know what to do for Emacs to execute the command.


Solution

  • For all kinds of interpreted languages, I use isend-mode, which allows sending parts of a buffer to a terminal in another buffer.

    Here is how you would use it (after having installed it):

    1. Open an ansi-term buffer:

      M-xansi-termRET/bin/bashRET

      and run an interactive perl session inside:

      perl -d -e 42RET

      Alternatively, install term-run.el and directly launch the interactive perl session in a term buffer:

      M-xterm-run-shell-commandRETperl -d -e 42RET

    2. Open the buffer with the code you want to execute, and associate it to the interpreter buffer:

      M-xisendRET*ansi-term*RET

    3. Hit C-RET in the perl buffer to send the current line to the interpreter in the ansi-term buffer. If a region is active, all lines spanning the region will be sent.


    Below is a proposed setup allowing to better take advantage of the perl debugger specific commands. With the following customization, x is prepended to all instructions (so that you see the results), except print commands.

    (defun isend--perl (buf-name)
      "Prepend 'x ' to normal perl instructions.
    Leave 'print' instructions untouched."
      (with-current-buffer buf-name
        (goto-char (point-min))
        (unless (looking-at "[[:space:]]*print")
          (insert "x ")))
      (insert-buffer-substring buf-name))
    
    (defun isend-default-perl-setup ()
      (when (eq major-mode 'perl-mode)
        (set (make-local-variable 'isend-send-line-function) #'isend--perl)))
    
    (add-hook 'isend-mode-hook #'isend-default-perl-setup)