Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Ovid (2709)

  (email not shown publicly)
AOL IM: ovidperl (Add Buddy, Send Message)

Stuff with the Perl Foundation. A couple of patches in the Perl core. A few CPAN modules. That about sums it up.

Journal of Ovid (2709)

Sunday November 08, 2009
05:42 AM

Stupid things to do with vim: run snippets

[ #39860 ]

Sometimes when I'm writing POD, I find that I want something like this:

use Test::More 'no_plan';
ok 1, '"1" is true';
is "foo", "foo", '"foo" equals itself';
ok 1 - "1" is true
ok 2 - "foo" equals itself

In other words, I want a snippet of code with the output displayed after the __END__ block. However, that means copying the code to a file, pasting the code, fixing the inevitable errors, rerunning, copying the output, putting vim in paste mode, typing the __END__ token, pasting in the output and putting vim back in nopaste mode.

That's a pain. Now I can just type ,rs (run snippet) on a section of code which I've selected via cntl-v. The vim mapping is:

vnoremap <silent> ,rs :!perl ~/bin/eval<cr>

And ~/bin/eval script is:

#!/usr/bin/env perl

use strict;
use warnings;
use File::Temp 'tempfile';

# create a temporary perl script file
my ( $fh, $snippet ) = tempfile(
    SUFFIX => '.pl',
    DIR    => '/var/tmp'
my $code = do { local $/; <STDIN> };
print $fh $code or die "Could not print code to ($snippet): $!";
close $fh or die "Could not close ($snippet): $!";

my $perl = $^X;
print $code, " __END__\n";
my $output = ' ' . qx{ $perl $snippet 2>&1 };
$output =~ s/\n/\n /g;
print $output;

That will run the snippet and automatically put the results after an __END__ token. This is a very dangerous (and fragile) technique, so use it with care.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.
  • Hey, that's nifty.

    But having ~/bin/eval may get confusing, the name clashing with the buit-in shell command eval. perleval would be less confusing (and a longer name doesn't really matter, since your mapping does the typing for you).

  • Nice idea. I used it in my .emacs but slightly differently. This evals the contents of the current region w/ perl-run-snippet-command and inserts it afterward as comments.

    (defvar perl-run-snippet-command
      "Command for running perl for `perl-run-snippet'")
    (defun perl-run-snippet (start end)
      "Execute `perl-run-snippet-command' on the current region. Insert the results as comments."
      (interactive "r")
      (let ((buffer (current-buffer))