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

Hi Monkies

Im wondering if there is a way to store to results of this action into an array rather than a text file. The problem with the text file option is that it will be stored on a server that doesn't give the program write permission.

The code is:

system("/usr/local/mysql/bin/mysql -u anonymous -h my.database.org --e +xecute='show databases' | grep $temp_choice > dblist.txt") ;

Output of which should give:
database_version1
database_version2
database_version3
database_version3.4
thus allowing me to find the most recent database on the other server.

cheers,
MonkPaul.

Replies are listed 'Best First'.
Re: Storing system results in an array
by swampyankee (Parson) on Feb 17, 2006 at 18:01 UTC

    I highly recommend reading the entry in the perldocs on open (perldoc -f open) and in the section on perlipc.

    .

    You can "open" system commands to a pipe by something like

    open($fh, "command |") or die "command wouldn't run...because $!\n"; @output = <$fh>;

    In your case, you could write something like this:

    my $command = "/usr/local/mysql/bin/mysql -u anonymous " . "-h my.database.org ". "--execute='show databases'"; open($fh, "$command |") or die "Could not execute $command because $!\ +n"; @results = <$fh>; @results = grep { /$temp_choice/} @results;

    or (reading the output a line at a time, vs slurping it up)

    while(<$fh>) { do_something if /$temp_choice/; }

    Note that this was not tested (I don't have mysql on my system) but it is syntactically correct.

    emc

    " When in doubt, use brute force." — Ken Thompson
Re: Storing system results in an array
by InfiniteSilence (Curate) on Feb 17, 2006 at 18:17 UTC
    I think the other posts do a good job of considering backticks and methods to do what you want. But considering what you are actually doing with the code you provided, you could do that using DBI:
    @data_sources = DBI->data_sources($driver_name, \%attr);

    Celebrate Intellectual Diversity

Re: Storing system results in an array
by Fletch (Bishop) on Feb 17, 2006 at 17:47 UTC

    perldoc perlop, look for backticks (``; aka qx//).

    Update: Alternately just open a pipe and read from that (which would also eliminate the need for an external grep).

Re: Storing system results in an array
by xdg (Monsignor) on Feb 18, 2006 at 01:20 UTC
    store to results of this action into an array

    In addition to the good comments given above, IPC::Run3 is the answer to the literal question that you asked. It's also fairly portable, whereas the techniques in perlipc may not be.

    use strict; use IPC::Run3; my (@in, @out, @err); run3( $your_command, \@in, \@out, \@err );

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.