Perl implementation of the CVS "solicit log entry by opening up an editor to type into" feature. Creates a temporary file, opens up the editor on the file, then pulls the file contents back into the program.
#!/usr/bin/perl -w use Fcntl qw(:DEFAULT :flock); use File::Temp qw(tempfile); use File::Spec; my $editor = $ENV{EDITOR} || 'vi'; # for naming temp files, so can chase down which app they are coming # from if problems crop up my ($ourname) = $0 =~ /([\w.-]+)$/; $ourname ||= 'perl'; File::Temp->safe_level(2); my ($tfh, $fname) = tempfile("$ourname.XXXXXXX", DIR => File::Spec->tmpdir, UNLINK => 1); # set autoflush to ensure editor gets the right data my $oldfh = select $tfh; $| = 1; select $oldfh; print $tfh <<"INTRO"; Default text to appear in editor. INTRO # File::Temp locks the file by default, which is not productive # with external editors that also want to lock the file. flock $tfh, LOCK_UN; my $status = system "$editor $fname"; die "external editor failed with $?\n" unless $status == 0; # deal with supplied data seek $tfh, 0, 0 or die "Error seeking on temp file: $!\n"; while (<$tfh>) { print; }

Replies are listed 'Best First'.
Re: Soliciting input via a tempfile passed to an external editor
by Aristotle (Chancellor) on Jan 23, 2003 at 20:14 UTC
    Nice. There's a bit of room to polish it a little:
    #!/usr/bin/perl -w use strict; use Fcntl qw(:DEFAULT :flock); use File::Temp qw(tempfile); use File::Spec::Functions qw(tmpdir); use File::Basename; my $editor = $ENV{EDITOR} || 'vi'; File::Temp->safe_level(2); my ($tfh, $fname) = tempfile( basename($0).".XXXXXXX", DIR => tmpdir(), UNLINK => 1, ); select((select($tfh), $|++)[0]); print $tfh <<"INTRO"; Default text to appear in editor. INTRO # File::Temp locks the file by default # which is not productive with external editors flock $tfh, LOCK_UN; my $status = system $editor, $fname; die($status != -1 ? "external editor $editor failed with $?\n" : "couldn't launch external editor $editor: $!\n" ) unless $status == 0; seek $tfh, 0, 0 or die "Error seeking on temp file: $!\n"; my $data = do { local $/; <$tfh> };
    Just minor changes, obviously.

    Makeshifts last the longest.

Re: Soliciting input via a tempfile passed to an external editor
by zengargoyle (Deacon) on Jan 24, 2003 at 01:01 UTC

    why not a Module ;(

    #!/usr/bin/perl use Editor; print Editor->new->solicit(<<"_INTRO_"); Insert text here. _INTRO_
      I really don't think this particular case warrants an OO approach. Editor::solicit() would be perfectly sufficient - though it all still needs better names.

      Makeshifts last the longest.