geeeeeo
geeeeeo

Reputation: 11

How to pass a variable from powershell to a Perl script?

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.

Upvotes: 1

Views: 316

Answers (2)

ikegami
ikegami

Reputation: 386561

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?

Upvotes: 3

Jesse
Jesse

Reputation: 1425

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

Upvotes: 1

Related Questions