3

So, In Strawberry Perl, %ENV appears to be an ordinary hash (at least it isn't tied), but it also appears to resolve keys case insensitively. This makes sense given that environment variables are case insensitive in PowerShell (I am not sure of the exact relationship between Windows environment variables and case). So, I am wondering how %ENV can simultaneously be an ordinary hash, and have "implicit" keys that are not listed when you call they keys builtin on it. Is the %ENV hash magical without being tied?

use strict;
use warnings;

# Env appears to be an ordinary hash
# 'TEMP' is present in the list of environment variables
# but 'temp' is not
printf "$_\n" foreach keys %ENV;

print "\n";

# this gives us the value of $ENV:TEMP
# which makes sense.
printf "uppercase 'temp' maps to %s\n", $ENV{TEMP};

# even though temp is not present in the
# list of keys, the same value appears as for
# $ENV{TEMP}
# This seems to make sense given the behavior of powershell
# (I am not quite sure what the relationship is between
# Windows environment variables and case, but this seems reasonable.)
printf "lowercase 'temp' maps to %s\n", $ENV{temp};

# However, %ENV is not a tied hash.
printf "Tie status: %s\n", tied(%ENV) // "not a tied variable";
Greg Nisbet
  • 6,710
  • 3
  • 25
  • 65

2 Answers2

5

The following is from ActivePerl, but every Perl including Strawberry Perl will give you the same thing:

>perl -E"use Devel::Peek; Dump(\%ENV, 1);"
SV = IV(0x74b154) at 0x74b154
  REFCNT = 1
  FLAGS = (TEMP,ROK)
  RV = 0x63e33c
  SV = PVHV(0x62a8ac) at 0x63e33c
    REFCNT = 2
    FLAGS = (SMG,RMG,SHAREKEYS)
    MAGIC = 0x639084                               <-------
      MG_VIRTUAL = &PL_vtbl_env
      MG_TYPE = PERL_MAGIC_env(E)
    ARRAY = 0x640794  (0:30, 1:22, 2:11, 3:1)
    hash quality = 107.7%
    KEYS = 47
    FILL = 34
    MAX = 63

As you can see, %ENV is magical. But it's not tied; that would be magic type "P" instead of "E".

ikegami
  • 367,544
  • 15
  • 269
  • 518
2

Is the %ENV hash magical without being tied?

Yes, %ENV is a magic variable without being tied, similar to various other variables like %SIG. See perldoc perlvar for more of these.

Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172