I tried to call another script using the following code
system("perl sample.pl");
How to pass value, array and hash to another script and how to get those values in sample.pl ?
I'm not sure if this is the best method, but you could use Data::Dumper and read the data from stdin.
#!/usr/bin/perl
use strict;
use warnings;
use FileHandle();
use Data::Dumper();
my %data = (
key => 'value',
arr => [ 0..5 ],
);
my $fh = FileHandle->new('| ./sample.pl') or
die "Could not open pipe to './sample.pl': $!\n";
print $fh Data::Dumper->Dump([\%data], [qw(data)]);
$fh->close();
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper();
my $str = do { local $/; <STDIN> };
my $data;
eval $str;
if ($@) {
die "Error in eval: $@\n";
}
$data->{key} = 'new value';
print Data::Dumper->Dump([$data], [qw(data)]);
$ ./test.pl
$data = {
'key' => 'new value',
'arr' => [
0,
1,
2,
3,
4,
5
]
};
You can pass them as command-line arguments with their type as one of the cmd line values
And then check that cmd-line value containing type, which will be in @ARGV, in other script as below:
mainscript.pl
use strict;
use warnings;
# Variable
my $ele = 10;
system("perl sample.pl $ele varval");
# Array
my @arr = (1,2,3);
system("perl sample.pl @arr arrval");
# Hash
my %h = (
'a' => 1,
'b' => 2
);
my @a = %h;
system("perl sample.pl @a hashval");
Sample.pl
use Data::Dumper;
print("\nIn sample\n");
if($ARGV[-1] eq 'varval')
{
print("\nIts var\n");
delete($ARGV[-1]);
print($ARGV[0]);
}
elsif ($ARGV[-1] eq 'arrval')
{
print("\nIts array\n");
delete($ARGV[-1]);
@temparr = @ARGV;
print(@temparr);
}
elsif ($ARGV[-1] eq 'hashval')
{
print("\nIts hash\n");
delete($ARGV[-1]);
my %h1 = @ARGV;
print(Dumper(\%h1));
}
Output:
D:\perlp>perl mainscript.pl
In sample
Its var 10
In sample
Its array 123
In sample
Its hash $VAR1 = { 'a' => '1', 'b' => '2' };
D:\perlp>
Why do you want to pass them via STDIN? I think its easier to write a short file before you start the system call. And read that file with the other script. You could pass the filename via STDIN, when you want to create a dynamic filename (when you have multiple executions or so).
Even when its a complex Object you want to pass. You could use that for Serialization. Its a CORE-Module.