Home > database >  How to pass a variable from powershell to a perl script
How to pass a variable from powershell to a perl script

Time:06-24

Sure this is a very easy answer for someone.

If i have the below saved as new.pl, how do i pass $name from the powershell command line to it so i can run and set the variable from PS

print "Hello, world, from $name.\n";

I tried start-process and using cmd.exe /C but don't really know what is needed. Thanks

CodePudding user response:

You'd simply use

perl a.pl $name

This provides the value in @ARGV.

use v5.20;
use warnings;

my ( $name ) = @ARGV;

say "Hello, world, from $name.";
PS> $name = "your friendly neighbourhood Spiderman"
PS> perl a.pl $name
Hello, world, from your friendly neighbourhood Spiderman.

As a one-liner:

perl "-Mv5.20" -e"say qq{Hello, world, from `$ARGV[0].}" $name

If you need to pass arguments while using -n or -p, see How can I process options using Perl in -n or -p mode?

CodePudding user response:

I found this answer which says you can use the -s command line switch in order to be able to pass arbitrary data. The example provided in this answer is this:

perl -se 'print "xyz=$xyz\n"' -- -xyz="abc"

The -e switch in this example just allows execution of code from the command line, which isn't necessary in this case because you're running a file, so we can just get rid of it. I'm not experienced with perl and can't find anything on what the -- does. If someone knows feel free to leave a comment and I will add it to the answer, but for now I'll just ignore it because it seems to work without it.

After these modifications, the command above would look something like this:

perl -s new.pl -name="joe"

Pretty simple. Now we can very easily convert this to a PowerShell command. perl is the program being ran, and everything else is arguments. using Start-Process it would look like this:

Start-Process perl -ArgumentList "-s new.pl -name=`"joe`""

Now this does work, but by default Start-Process creates a new window, so it's opening the perl interpreter which just instantly closes because there's nothing telling it to wait. If you want it to print the output to the PowerShell window, you can just use the -NoNewWindow switch.

Start-Process perl -ArgumentList "-s new.pl -name=`"joe`"" -NoNewWindow

CodePudding user response:

Adding my ( $name ) = @ARGV; to the perl script allowed me to pass the variables needed from the command line .\new.pl $variable1

  • Related