Opening and Reading Registry Values

Let’s start our exploration of the Registry by finding out how to get information out of it. As an example, let’s see what we can find out about the current build version of Windows NT on our system. If you’re using this book on a Windows 95 system, you’ll need to change the Windows NT key to Windows:

use Win32::Registry;
$p = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";
$main::HKEY_LOCAL_MACHINE->Open($p, $CurrVer) || 
        die "Open: $!";
$CurrVer->GetValues(\%vals); # get sub keys and value -hash ref
foreach $k (keys %vals) {
    $key = $vals{$k};
    print "$$key[0] = $$key[2]\n"; # see below for explanation
}

Running this script on one of our systems produces the following output:

CurrentBuildNumber: 1381
CSDVersion = Service Pack 3
CurrentBuild = 1.511.1 () (Obsolete data - do not use)
RegisteredOrganization = Axiom Technologies
CurrentType = Uniprocessor Free
InstallDate = Ö?L3
RegisteredOwner = Erik Olson
CurrentVersion = 4.0
SystemRoot = D:\NT
CurrentBuildNumber = 1381
SoftwareType = SYSTEM
ProductId = 50036419013877247607
SourcePath = E:\I386
PathName = D:\NT

Let’s see what’s going on here. The first line of the script employs the use operator to include the Win32::Registry package. We then have a variable $p containing a Registry path relative to HKEY_LOCAL_MACHINE. The third line uses $main::HKEY_LOCAL_MACHINE (one of the Registry keys declared in registry.pm that we mentioned) to open the CurrentVersion key. If the Open method succeeds,

Get Learning Perl on Win32 Systems now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.