Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return array value from one Perl script to another Perl script

Tags:

arrays

perl

I have 2 scripts, say main_script.pl and secondary_script.pl

First I am running the main_script.pl which calls seconday_script.pl.

Code looks below for main_script.pl:

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

my $var1 = "val_1";
my $var2 = "val_2";

my $sec_script = "/home/shared/Vinod/Perl_Test/secondary_script.pl";
my $result = `perl $sec_script $var1 $var2`;

print "Result:$result\n";

secondary_script.pl

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

my $arg1 = $ARGV[0];
my $arg2 = $ARGV[1];

....
....
# DO SOME OPEARTION BY USING THE ARGUMENTS PASSED FROM main_script.pl
# FINALLY CREATE AN ARRAY @data

print Dumper(\@data);

Here I can able to generate output in array @data. But how can I pass this @data values to main_script.pl so that it will get stored in result.

Since in main_script.pl I have declared result as an scalar variable. My data value from secondary_script.pl would be array, so should I make result as an array variable? and how can I capture the data in main_script.pl?

like image 974
vkk05 Avatar asked Jun 12 '26 23:06

vkk05


1 Answers

In the secondary script, you can join the values with a known seperator, say |. In het main script you can split the string you receive on that seperator to get your array.

To give an idea how that could work:

use Data::Dumper;

my @arr = ("1", "3", "", "5");    
my $result = join ('|', @arr);   # in secondary script. print to stdout 
print STDERR Dumper(split( /\|/, $result));  # in main script: undo join

There is an edge case: if the first or last string of the array is an empty string, it will get lost and you have to do some extra tricks to account for that.

like image 176
ruud Avatar answered Jun 17 '26 23:06

ruud