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

Hello, I am a beginner at perl and i have very little experience with it. I am using a perl script like test.pl which has lines like
system("/root/node/ant run ");
I call this from a shell
% ./test.pl
what should i add to my script so that results of my executed command are visible in this shell? for e.g
system("/root/node/ant run ");
generates an o/p line like
" Welcome"
So when i run ( expected output) % ./test.pl " Welcome" %

2006-01-13 Retitled by planetscape, as per Monastery guidelines
Original title: 'Need to display o/p from shell'

Thank you all for the replies. I used the file handle method.

Replies are listed 'Best First'.
Re: Need to display output from shell
by aufflick (Deacon) on Jan 13, 2006 at 00:05 UTC
    First - please change o/p to output in your title (I assume that's what it stands for) - otherwise you're making people read your entire post to understand the subject.

    Second - you are already doing it right, if I understand what you want to do. eg:

    #!/usr/bin/perl -w use strict; system("echo foo");
    will print foo to the screen.

    There are basically three ways to run system commands (there's a lot more, but for now these will do:

    #!/usr/bin/perl -w use strict; my $res = system("/sys/command");
    The standard out of the command will be printed to the screen and the perl variable $res is the return value of the command (ie. 0 for successful execution).

    The other way is with backticks which are the backwards apostraphes on your keyboard. eg:

    #!/usr/bin/perl -w use strict; my $res = `/sys/command`;
    Thi this case, nothing is printed to your screen and the perl variable $res is set to the entire standard out of your command.

    The third way is to treat it like a file pipe - this way is best for a lot of output:

    #!/usr/bin/perl -w use strict; my $file_handle; open $file_handle, "/sys/command |" or die "unable to open command as +pipe"; while my $line = ( <$file_handle> ) { chomp $line; # remove new line do_something( $line ); }
    Which way is best depends on what you're trying to achieve.
Re: Need to display output from shell
by vennirajan (Friar) on Jan 13, 2006 at 05:19 UTC
    Hi,

          Using "system" command you can execute only the commands and you cannot get the return value from them. For this requirement you have to use the backtick operator "``" in your code. Try to avoid this type of programming. Because this functions make your code a OS dependent. Next time you need to change your coding when you export your code for another OS. Always try to use the existing functionalities in perl. That also works speed than the "system" commands.



    Regards,
    S.Venni Rajan.
    "A Flair For Excellence."
                    -- BK Systems.