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

Hi All, I currently have the following statements:
system("diff $file1 $file2 | sed -re '/^[><]/d' >| temp.txt"); open (FILE, 'temp.txt'); @diffs = <FILE>;
is there anyway to get the results from my system call straight into the array without having to use a file? Any help would be great! :)

Replies are listed 'Best First'.
Re: using system() and putting results into an array
by targetsmart (Curate) on May 21, 2009 at 13:14 UTC
    use backticks ``
    see qx also

    Vivek
    -- In accordance with the prarabdha of each, the One whose function it is to ordain makes each to act. What will not happen will never happen, whatever effort one may put forth. And what will happen will not fail to happen, however much one may seek to prevent it. This is certain. The part of wisdom therefore is to stay quiet.
Re: using system() and putting results into an array
by jwkrahn (Abbot) on May 21, 2009 at 13:43 UTC
    open my $PIPE, '-|', 'diff', $file1, $file2 or die "Cannot open pipe f +rom 'diff' $!"; my @diffs = map { s/^[><]//; $_ } <$PIPE>; close $PIPE or warn $! ? "Error closing 'diff' pipe: $!" : "Exit status $? from 'diff'";
Re: using system() and putting results into an array
by johngg (Canon) on May 21, 2009 at 13:57 UTC

    You can open a filehandle on a piped command and you can also use Perl's built-in grep to do what sed does in your code. Here's an example applied to a couple of nonsense files.

    $ diff dddd eeee 2c2 < werfef --- > werftef 7c7 < esdd --- > es4dd $ $ diff dddd eeee | sed -re '/^[><]/d' 2c2 --- 7c7 --- $

    The script to do the same job.

    use strict; use warnings; my $file1 = q{dddd}; my $file2 = q{eeee}; my @diffs = do{ open my $diffFH, q{-|}, qq{diff $file1 $file2} or die qq{fork: diff $file1 $file2: $!\n}; grep ! m{^[><]}, <$diffFH>; }; print for @diffs;

    The output, which is identical to that produced by diff and sed on the comand line.

    $ ./spw765446 2c2 --- 7c7 --- $

    I hope this is useful.

    Cheers,

    JohnGG

Re: using system() and putting results into an array
by Bloodnok (Vicar) on May 21, 2009 at 13:32 UTC
    As targetsmart has already correctly pointed out, the backtick/qx operators are your friend in this case - system does nothing with STDIN or STDERR and returns nothing other than the error code and the signal number from the sub-process.

    A user level that continues to overstate my experience :-))
Re: using system() and putting results into an array
by tokpela (Chaplain) on May 22, 2009 at 08:18 UTC

    You might also want to look at String::Diff so that you don't even need to run a system call.

      Thanks everyone for your help! :)