windowsperlshellgit-bashactiveperl

Access Perl environment (shell) variables in Windows - $ENV not working


The issue

I found out how to use windows environment variables (e.g., %AppData%, %HomePath%, %SystemRoot%, etc.) in this SO post:

Getting the path of %AppData% in perl script

Here is the code snippet that was chosen as a working, correct answer:

 #!/usr/bin/perl

 use warnings;
 use strict;

 my $localConfPath = $ENV{localappdata};
 my $appdata = $ENV{appdata}; 

 print $localConfPath;  #will print the app path - C:\users\xxx\AppData\local
 print $appdata; #prints - C:\users\xxx\AppData\Roaming

However, this is not working on my machine in my code for some reason. My scripts work without the shebang (#!) line so I tried the script both with and without it, to no avail.

My set-up

I'm using the Perl that comes with GitBash, if that makes a difference.

What I've tried

I tried a simple Perl command line execution:

perl -e 'print %ENV{AppData}';

This didn't work. I also tried the following alternatives:

perl -e 'print %ENV{APPDATA}';
perl -e 'print %ENV{appdata}';

That also didn't work. Here's the error I get (the same for all 3 versions):

syntax error at -e line 1, near "%ENV{AppData"
Execution of -e aborted due to compilation errors.

I even tried to use the code from the SO post I mentioned in it's own file. That code doesn't work either. With the code from the post I get this error:

$ perl /c/Users/User1/Desktop/ehCode_testingWindowsEnvironmentVariables_01.pl
Use of uninitialized value in print at /c/Users/User1/Desktop/ehCode_testingWindowsEnvironmentVariables_01.pl line 7.
Use of uninitialized value in print at /c/Users/User1/Desktop/ehCode_testingWindowsEnvironmentVariables_01.pl line 8.

The lines in question then are these:

print $localConfPath;  #will print the app path - C:\users\xxx\AppData\local
print $appdata; #prints - C:\users\xxx\AppData\Roaming

I don't see why they shouldn't work.

I've checked Perl Monks, Perl Maven, Stack Overflow, and other popular Perl resources, to no avail. Even Active State did not have the answer.


Solution

  • When you access individual items of a hash, you need to use the scalar sigil, $ as opposed to the hash sigil, %:

    perl -e 'print $ENV{APPDATA}'