Kickstart has asked for the wisdom of the Perl Monks concerning the following question:

I'd like to not automatically execute the selected command, but print it to the command line so that I can edit it before I decide to run it, but I'm not sure how to do this. Suggestions? (Note that this is just the bare bones of the current script for illistration purposes. The real one has more error checking.)
$pattern = $ARGV[0]; @list = `grep $pattern $HOME/.bash_history`; @list = reverse @list; foreach $command (@list) { chomp $command; print "$command (Y/N)?"; $choice = <STDIN>; if ($choice =~ 'Y' || $choice =~ 'y') { $foo = `$command`; print "$foo\n"; exit; } }

Replies are listed 'Best First'.
Re: command recall
by ahunter (Monk) on Feb 12, 2001 at 14:53 UTC
    There isn't really an easy way you can send the command to a shell for editting (the only way I could think of was using ptys, and that would be overkill for such a little script :-)

    However, help is at hand in the form of Term::ReadLine, which can be used to create a line editor similar to that used by shells like bash:

    use strict; use Term::ReadLine; my $term = new Term::ReadLine 'readline demo'; my $line = $term->readline(">> "); print "Line was: $line\n";
    Although note that the capabilities tend to vary depending on how your version of perl was compiled, as the readline library is not always available.

    Andrew.

Re: command recall
by jynx (Priest) on Feb 13, 2001 at 02:05 UTC

    Update: this node has been changed from it's original post, it has been posted to try to answer the question

    hmm, how about something like:

    my $pattern = shift; #get the lines you're looking for in the file open HIST, "$HOME/.bash_history" or die "Couldn't open history file: $ +!\n"; my @list = grep { /$pattern/ and chomp and $_ } <HIST>; close HIST; #ask and run the commands foreach my $com (@list) { print "run [$com] (y/n)? "; my $ans = <STDIN>; $ans =~ /^y/i && do { my $result = `$com`; # error checking here print "result: $result\n"; }; }
    The only major difference is that most everything is kept in perl which allows for more error checking (like dying if the file doesn't exist or can't open, which you could check anyway, but hey =).

    There really isn't much difference between the two, but i think you typoed on the binding operator ($choice eq 'Y' is fine, but $choice =~ 'Y' doesn't make much sense).

    HTH,
    jynx

      >There really isn't much difference between the two, but i think you typoed on the binding operator >($choice eq 'Y' is fine, but $choice =~ 'Y' doesn't make much sense).

      Nah, I did that to avoid people being silly and typing 'Yes' or 'yes' instead. This way, if the inputted string contains Y or y it will still catch it. Unless the user (me) is silly enough to type 'Ny' or something.

      Greg