Bill
Bill

Reputation: 1247

In perl passing a parameter to a script using a required command

I have two file tmp.pl and tmp2.pl. I want to call tmp2.pl with a require command but also send a parameter. Is there a better way of doing this?

tmp.pl

require "tmp2.pl" "passed parameter";

tmp2.pl

print @_;

Upvotes: 0

Views: 2348

Answers (4)

ddoxey
ddoxey

Reputation: 2063

Supposing that you want to execute other program and capture its output I'm partial to using the IPC::Run module.

#!/usr/bin/perl

use strict;
use warnings;
use IPC::Run qw( run );

run( [ './tmp2.pl', @ARGV ], \'', \my $out, \my $err );

print "out: $out\n";
print "err: $err\n";

Upvotes: 0

marIO
marIO

Reputation: 1

Yes, I think this should work. Use "require" to include the script. After that you can pass the parameter by calling the sub function. The modified script can be

require "tmp2.pl" ;
subfunc(parameter);
print @_;

Upvotes: 0

mob
mob

Reputation: 118595

There's probably a better way to accomplish whatever it is you're trying to do, but you could achieve your current sub goal with something like

{
    local @_ = ("passed parameter");
    require "tmp2.pl";
}

I might consider this idiom in a place where I wanted to run a perl script from within a perl script. That is, I could say

{
    local @ARGV = ("foo","bar");
    require "my_script.pl";
}

instead of

system("perl","my_script.pl","foo","bar");

(There are plenty of subtle and not-so-subtle differences between these two calls, so a lot depends on what "features" of these calls you need)

Upvotes: 2

pavel
pavel

Reputation: 3498

As far as I know, require cannot be used to send a parameter. But that's a good thing, I think, because I cannot think of a reason why you should want to. Looks to me that your design is wrong.

tmp2.pl should be either:

  • a independent perl program, which you should run with system or qx()
  • a module, with optional exported tags etc.
  • a package which defines a class

but that's just my idea....

Upvotes: 4

Related Questions