perl command line backticks with matrix

176 views Asked by At

I'd like to transfer a matrix from one perl file to another by using a command line with backticks.

On the first file perl, source.pl :

use warnings;
use strict;

my @matrix = (
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
);

my $results = `perl other_file.pl @matrix`; #option 1
# my $results = `perl other_file.pl '@matrix'`; #option 2
print $results;

On other_file.pl

use strict
use warnings

my @matrix_other = $ARGV[0];
print "mat_adress = ".$matrix_other[1][2]."\n";

After launch source.pl, the terminal output:

  • with option 1 : sh: 1: Syntax error: "(" unexpected
  • with option 2 : Can't use string ("ARRAY(0x6c0cb8) ARRAY(0x6df410) "...) as an ARRAY ref while "strict refs" in use at other_file.pl line 5.

I've also try to use Symbolic references without success in other_file.pl (output was : "Not an ARRAY reference at other_file.pl")

Any idea ? Thanks a lot.

PS: No problem with a simple variable $var in the command line;

1

There are 1 answers

0
Sobrique On BEST ANSWER

OK, pretty fundamentally - to do what you're trying to do directly isn't possible. An array is a memory state, and it doesn't conveniently package up to pass it around. That's why you're getting things like ARRAY(0x6c0cb8) - that's because it's the memory address the array (or subelements) occupy.

So however you do this, you will need to render your array first, and then parse it in your subprogram.

This is a sufficiently big topic that there's a whole section of the documentation about it: perlipc

Approach to take varies a lot depending on what exactly you're trying to accomplish. For what you're trying to do, my first thought would be to look at Storable:

use warnings;
use strict;

use Storable;

my @matrix = ( [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] );

my $tempfile = "matrix.$$";
store \@matrix, $tempfile;

my $results = `perl other_file.pl $tempfile`;    #option 1
print $results;

and in 'other_file' use retrieve:

use warnings;
use strict;
use Data::Dumper;

use Storable qw/retrieve/;

my ($filename) = @ARGV;

print Dumper retrieve($filename);

(Although you should probably use File::Temp rather than arbitrary names for tempfiles).

However take a look at perlipc which has a LOT more on how to pass information back and forth.