I have 2 perl files. 1st file is my main program and the 2nd is a small sub which I call by using system("file.pl"); I would like to reuse a stored value/s in variables from the main program and use them in the external file. How is this possible?

I have 2 perl files. 1st file is my main program and the 2nd is a small sub which I call by using system("file.pl"); I would like to reuse a stored value/s in variables from the main program and use them in the external file. How is this possible?

Main script calls perl and passes the name of another script plus a couple of values for the second script to print.

#!/usr/bin/perl
use strict; 
use warnings; 

my $command = '/usr/bin/perl';
my $script = '/home/david/Programming/Perl/print_values.pl';
my $value1 = 'Boiling point of water';
my $value2 = '100 degrees celsius';

system($command, $script, $value1, $value2) == 0
    or die "system $command, $script, $value1, $value2 failed: $?"

print_values.pl

#!/usr/bin/perl
use strict; 
use warnings; 

my ($v1, $v2) = @ARGV;

print "First variable contains '$v1'\n";
print "Second variable contains '$v2'\n";

Have a look at this similar question on StackOverflow. I like the following idea:

#!/usr/bin/perl
use strict; 
use warnings; 

my $command = '/usr/bin/perl';
my $script = '/home/david/Programming/Perl/print_values.pl';
my $value1 = 'Boiling point of water';
my $value2 = '100 degrees celsius';

{
    local @ARGV = ($value1, $value2);
    unless (my $return = do $script) {
        warn "couldn't parse $script: $@" if $@;
        warn "couldn't do $script: $!"    unless defined $return;
        warn "couldn't run $script"       unless $return;
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.