0

So I have two variable one is a string and the other is a list . How do I pass the string and the list to another Perl file?

This is my python code

import subprocess
import os 
method = "add"
server_info  = [1,2,3,4,5,6,7,8,9]

ping = subprocess.Popen(["perl","file1.pl"]+method+server_info)
output, errors = proc.communicate()

And my perl file i.e file1.pl contains this code

#!/usr/bin/perl

my ($method, @server_info) = @ARGV;

print $method;
for(i=0;i<len(@server_info);i++)
{
   print @server_info[i]
}

And I'm facing this error

TypeError: can only concatenate list (not "str") to list
brian d foy
  • 129,424
  • 31
  • 207
  • 592
RAJ MANI
  • 17
  • 5
  • 2
    How do you know it doesn’t work? See how to create a [mcve] and edit the question. – Peter Wood May 16 '21 at 09:16
  • [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) help to reproduce and clear problem statement would help others to learn too. – thirdeye May 16 '21 at 09:30
  • 3
    You need to think not about passing parameters between "files" but "processes". Look up IPC (interprocess communication). Writing the list as JSON from Python to Perl's STDIN might be a good solution. – tobyink May 16 '21 at 11:14
  • Yes , I have created a minimal reproducible example but just need to know how do I pass the variables method and server_info to my perl file – RAJ MANI May 16 '21 at 11:19
  • 3
    `len()` is not a Perl function. `length()` however is. You should always use `use strict; use warnings` when writing Perl code, otherwise many errors will be silent. – TLP May 16 '21 at 12:02

1 Answers1

0

Like the error message suggested, replace the string with a list or similar.

>>> ["perl","file1.pl"]+method+server_info
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
>>> ["perl","file1.pl"]+[method]+server_info
['perl', 'file1.pl', 'add', 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

As a side note, there are numerous issues with the Perl program.

#!/usr/bin/perl

use 5.014;      # ALWAYS use "use strict" or an equivalent. This also introduces `say`.
use warnings;   # ALWAYS use this.

my ($method, @nums) = @ARGV;

say $method;              # `say` adds a line feed, unlike `print`.

for my $i (0..$#nums) {   # So much simpler. Added missing sigils (`$`).
   say $nums[$i];         # Replaced slice (`@a[]`) with array lkup (`$a[]`).
}

or

for my $num (@nums) {     # So much simpler.
   say $num;
}

or

say for @nums;
ikegami
  • 367,544
  • 15
  • 269
  • 518