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

I am writing a CGI script that uses the UNIX command, diff. I want to store the output of he diff command, so that I can manipulate it. Unfortunately, diff just keeps sending the output to standard out, the browser. I've tried:
my $foo = system("diff $args $file1 $file2");
as well as
my $foo = `diff $args $file1 $file2`;
Any suggestions? Thanks in advance

Replies are listed 'Best First'.
Re: diff output; unix commands
by bedk (Pilgrim) on Jan 23, 2002 at 23:33 UTC
    open FOO, "diff $args $file1 $file2 |"
    then reading from <FOO> should do the trick.
Re: diff output; unix commands
by webengr (Pilgrim) on Jan 24, 2002 at 00:08 UTC
    I think that to make it work the way you tried, you need to have the call to diff return a list context. Try this,
    @lines = (`diff $args $file1 $file2`); for (@lines) { print; }
    It may not be exactly what you want, in that it captures all of the output into an array.

    Or, if you really want the output from diff in a scalar as a single string, then you need to (temporarily) change the input record separator $/ to something other than newline, typically the null value will suffice. This snippet will accomplish the task:

    { local $/ = '\0'; $line = `diff $args $file1 $file2`; print $line; }
    bedk's solution is probably better because you can filter the output from diff one line at a time through a regex, and save/process only the lines you want.
    Cheers,
    PCS
Re: diff output; unix commands
by PrakashK (Pilgrim) on Jan 24, 2002 at 04:07 UTC
    If you can, use Text::Diff.
    use Text::Diff; my $foo = Text::Diff::diff $file1, $file2, \%options;
    %options include STYLE (unified, context or classic etc), OUTPUT and a couple others.

    /prakash