Question:
How to run a perl script in another perl script??
broad
2008-06-08 23:59:57 UTC
Let's say i have a perl script "Example.pl" which returns "hello".I want another perl script "example2.pl" which will run the example.pl and give a output like "hello there!".is there any way to do it?
Four answers:
DaveE
2008-06-09 14:35:22 UTC
Assuming "Example.pl" saves its output to "file.txt", and that its output is "hello", then you'd want something like this:



my($OUTPUT);

system("Example.pl"); #Assumes Example.pl executes successfully!

open($OUTPUT,"file.txt"); #Assumes filehandle open is successful

while(my $line = <$OUTPUT>) {

print $line;

}

close $OUTPUT;

print " there\n";



Of course, you can simplify this a bit, but for the sake of understanding and learning, it's a little lengthier than it needs to be.



DaveE
Nathan V
2008-06-09 07:29:05 UTC
There are several ways:



#1 - you can include/execute the Perl code stored in another source file by telling the Perl compiler to do so using the require statement:



require "use_this_files_source.pl";



#2 - You can create a system() call to have the operating system run a process, (this works weather the other program is written in Perl or any other language for that matter), something like this:



system("/path/to/some/perl/program.pl");

or system("/path/to/some_other_type/of_program");



#3 - You can use backticks (``) to call an external program, (same as system() does), in order to call an external program AND make use of it's output. The backticks instruct the Perl compiler to open/run the requested external program and re-direct it's standard output, like so:



my $lines = `cat /some/textfile.txt`;

or print `somecommand_that_outputs_something`;



If you clarify what it is you're trying to do, a clearer answer could be provided. Also - you could use Perl modules, but since your question indicated the other file was a Perl program, I didn't get into how modules work.
Rams
2008-06-09 07:12:41 UTC
you can include the Example.pl file which has output "hello" in Example2.pl which has out put "there".

then you will get out from Example2.pl like "hello there"



use this function

require "Example.pl";

Print "there";
simultaneous
2008-06-11 04:14:11 UTC
a good way to simply "shell" another perl script is via the "do" command.



These 2 scripts will actually work if you paste them and run them.... I think that's the most useful way to answer perl questions:



--- example2.pl ----



do("example2.pl");

my $out = grab("out.txt");

print $out;

print " there\n";



# this is a favorite function of mine

sub grab {

local $/ = undef;

open GIN, "out.txt";

my $r = ;

close GIN;

return $r;

}



--- example.pl ----



open OUT, ">out.txt";

print OUT "hello";

close OUT;



-----------------------


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...