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

I need to run a program from with in a Perl script, which will display information on the screen and capture that data into a variable. I can run a program with in a Perl script and see the data on the screen, and I can run a program with in a Perl script and capture the data into a variable, but I can not do both. For example doing a more on a file. I need to watch the more happen and capture that data in variable and storing it away. Any ideas on how do to this?
  • Comment on Executing a program with in a perl script, and capturing the data in two ways

Replies are listed 'Best First'.
Re: Executing a program with in a perl script
by lhoward (Vicar) on Aug 15, 2000 at 22:16 UTC
    How about something like this:
    open F,"somecmd |" or die "error spawning command $!"; my $data=''; while(<F>){ $data.=$_; print; } close F;
      Thanks that worked great. I did see something like this before but the explaination of what it does did not match what I was looking for. Once again thank you.
Re: Executing a program with in a perl script
by Shendal (Hermit) on Aug 15, 2000 at 22:17 UTC
    I'd suggest using open. Breifly, it would work something like this:
    #!/usr/bin/perl -w use strict; my($program) = 'cat'; my(@ary); open(CAT,"$program ~/foo.txt |") || die "Unable to run $program: $!\n" +; foreach (<CAT>) { push @ary, $_; print "$_"; } close(CAT);
    Of course, TIMTOWTDI, with backticks, for example. However, this method has worked well for me in the past.

    Note: Taint checking is left as an exercise for the reader.

    Hope that helps,
    Shendal
Re: Executing a program with in a perl script
by ferrency (Deacon) on Aug 16, 2000 at 00:56 UTC
    Both lhoward's and Shendal's answers are good examples of what I think is a more general Way To Think About The Problem: If you can capture the data into a variable, just print the variable, and then the results are on the screen as well.

    Another example (backticks, as Shendal mentioned):

    my $answer = `/usr/local/bin/arbitrary_script_that_prints_something`; print $answer;
    If you're writing short scripts or one-liners, you might man perlrun and check out the -e, -n, and -p options. In short scripts these can remove 90% of the skeleton code for you.

    Alan