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

Hi guys, I am running a command in command prompt say for example "hostname" in perl using system("hostname") I need to get the output generated by the command into the program flow directly without putting it into a file please let me know how to do this thank you

Replies are listed 'Best First'.
Re: how to get cmd prompt output
by davido (Cardinal) on Sep 08, 2006 at 05:04 UTC

    Instead of system, you might want to use qx// or the `backticks`. The purpose of those constructs is to capture output of your shell commands.

    Have a look at perlop for details.

    Example:

    perl -e "print reverse qx/dir/;"

    ...(for Windows) or ....

    perl -e 'print reverse qx/ls -l/;'

    ...(for unix/linux).


    Dave

Re: how to get cmd prompt output
by planetscape (Chancellor) on Sep 08, 2006 at 05:19 UTC
Re: how to get cmd prompt output
by McDarren (Abbot) on Sep 08, 2006 at 05:08 UTC
    system returns the exit status of the external program, which is not what you are after. To capture the output of the external proram, there are a few options.

    The simplest is to use backticks, for example:

    chomp(my $hostname = `/bin/hostname`); # Note that the chomp is necessary to remove the trailing newline

    Another option is to open a piped filehandle, eg:

    my $cmd = '/bin/hostname'; open (IN, "$cmd|"); chomp(my $hostname = <IN>);

    But neither of the above methods are portable. So as usual, CPAN is your friend. Take a look at Sys::Hostname.

    Cheers,
    Darren :)

Re: how to get cmd prompt output
by Zaxo (Archbishop) on Sep 08, 2006 at 05:11 UTC

    That's what backticks, aka qx, are for.

    defined( my $hostname = `/bin/hostname`) or die "No host";
    I've used the absolute path to hostname to remove a possibly insecure dependence on $ENV{PATH}.

    After Compline,
    Zaxo