Reputation: 37
I am trying to call a second script from the main script. When I am passing the argument in the command itself using capture, it's working. But when I am trying to send the command and arguments separately in capture function it's giving me an error that it can't find the specified file.
Second script
#!/usr/bin/perl
use 5.010;
use strict;
use warnings;
my $word= $ARGV[0];
my $crpyt = "$word crypted";
print "$crpyt\n";
my $decrypt = "$word decrypted";
print "$decrypt\n";
main.pl
#!/usr/bin/perl
use 5.010;
use strict;
use warnings;
use IPC::System::Simple qw(capture capturex);
my $cmd= 'perl xyz.pl Hello';
my @arr = capture($cmd);
print "$arr[0]";
print "$arr[1]\n";
This is working Output:
Hello crypted
Hello decrypted
BUT main.pl
#!/usr/bin/perl
use 5.010;
use strict;
use warnings;
use IPC::System::Simple qw(capture capturex);
my $cmd= 'perl xyz.pl';
my @arg=("Hello");
my @arr = capture($cmd,@arg);
print "$arr[0]";
print "$arr[1]\n";
This is not working. It says
"perl xyz.pl" failed to start: "The system cannot find the file specified" at main.pl line 11
Upvotes: 0
Views: 152
Reputation: 385917
If you only pass a single scalar, capture
expects it to be a shell command.
As such, capture('perl xyz.pl Hello')
works.
If you pass multiple scalars, capture
expects the first to be a path to a program to execute. The rest are passed as arguments.
As such, capture('perl xyz.pl', 'Hello')
doesn't work.
You could use
use IPC::System::Simple qw( capture );
my @cmd = ( 'perl', 'xyz.pl', 'Hello' );
capture(@cmd)
But you never want to use capture
unless you pass a single scalar that's a shell command. Use capturex
when passing a path and arguments.
use IPC::System::Simple qw( capturex );
my @cmd = ( 'perl', 'xyz.pl', 'Hello' );
capturex(@cmd)
But let's say you get the string perl xyz.pl
from elsewhere. A shell needs to be invoked, so we need to convert the arguments in to shell literals.
use IPC::System::Simple qw( capture );
use String::ShellQuote qw( shell_quote );
my $cmd = 'perl xyz.pl';
my @extra_args = 'Hello';
my $full_cmd = $cmd . ' ' . shell_quote(@extra_args);
capture($cmd)
Alternatively,
use IPC::System::Simple qw( capturex );
my $cmd = 'perl xyz.pl';
my @extra_args = 'Hello';
capturex('sh', '-c', 'eval $0 "$@"', $cmd, @extra_args)
Upvotes: 3