a1111exe
a1111exe

Reputation: 641

Perl: redirect multi line text to editor and return edited text into variable

Is there any way to print multi line text from variable to some editor, that on exit will return the edited text to the script?

Like:

my $result = `echo -n $txt | some_editor`;
print $file_handle $result;

Upvotes: 1

Views: 114

Answers (3)

Todd
Todd

Reputation: 746

Proc::InvokeEditor is another module that does this quite well.

Upvotes: 0

DavidO
DavidO

Reputation: 13942

It looks to me like Term::CallEditor is probably a good approach. vipe is available from the moreutils package that can be installed using a package manager, but it is not on CPAN. Term::CallEditor is available on CPAN, and has also probably been picked up by many package management repos.

vipe from moreutils invokes vi. Term::CallEditor's solicit command invokes the editor pointed to by the EDITOR environment variable, which is a more *nix-y way to do things; it's what people generally expect. In the absence of an EDITOR environment variable it will fall back to vi.

From the SYNOPSIS in Term::CallEditor's POD.

   use Term::CallEditor qw/solicit/;

   my $fh = solicit('FOO: please replace this text');
   die "$Term::CallEditor::errstr\n" unless $fh;

   print while <$fh>;

I like that solicit respects the $ENV{'EDITOR'} variable, which is similar to how git works, for example.

Looking at the code from Term::CallEditor, it's really not that substantial nor complex, but given the module exists I wouldn't see any reason to try to duplicate its handling of edge cases myself.

If vipe respects $EDITOR too, then it would come down to an assessment of what other features each module provides, and a deeper code review. Or just pick one and go with it. I still may favor Term::CallEditor because it is on CPAN.

Upvotes: 1

a1111exe
a1111exe

Reputation: 641

Ok, I have suddenly found the way to do this. There is a 'vipe' tool in 'moreutils' package. So after sudo apt-get install moreutils (in my case the system is Ubuntu) the code should become:

my $result = `echo -n $txt | vipe`;
print $file_handle $result;

In my case the default editor is Vim (in my system vipe uses editor from 'EDITOR' environment variable, with rollback to vi if 'EDITOR' is undefined), so the text is opened in Vim under temporary file in '/tmp' - after :wq Vim command the editor is closed, the temporary file is deleted and the contents return to '$result' variable. Great!

Upvotes: 1

Related Questions