home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


16.6 Setting Registry Values

In addition to creating keys, we can also set Registry values. To do so, we once again need an open key and the SetValue or SetValueEx function. SetValue sets the default (unnamed) value for a key, while SetValueEx allows you to create a new named value and set its information. The following example assumes that we already have the $eriko key open:

$eriko->SetValue("blah", REG_SZ, "some_string");
$eriko->SetValueEx("foo", 0, REG_SZ, "bar");

Even though these two functions look similar, they do quite different things. The first line ( SetValue ) creates a new key called blah and sets its default (unnamed) value to some_string . The second line ( SetValueEx ) creates a new value under $eriko with a name of foo and a value of bar . In both cases, we're using the REG_SZ data type, which indicates string data.

16.6.1 More Registry Operations

You can do more with the Registry than just read and modify key values. You can also delete keys and export/import hives from the Registry. As we mentioned above, be extremely prudent when deleting or importing things into your registry.

Here's an example of deleting a key:

use Win32::Registry;
$main::HKEY_CURRENT_USER->Open("SOFTWARE", $Software) || 
        die "Open: $!";
$Software->Create("ERIKO", $eriko) || 
        die "Create: $!";     # open parent key
$eriko->DeleteKey("blah"); # delete blah 

DeleteKey will delete a key and all of its values - it will not delete a key with subkeys. To do that, you need to remove all of the subkeys first. Here's how you do that:

use Win32::Registry;
$main::HKEY_CURRENT_USER->Open("SOFTWARE", $Software) || 
        die "Open: $!";
$Software->Create("ERIKO", $eriko) || 
        die "Create: $!";
$eriko->Open("blah", $blah); # open blah 
$blah->GetKeys(\@kids);      # get all child keys
foreach $k (@kids) {         # kill all of them
    $blah->DeleteKey($k);
} 
$eriko->DeleteKey("blah");   # now, remove blah

This code assumes that none of the child keys of blah have child keys themselves. If they do, you'll need to do something recursive to iterate over each subkey and all of its subkeys.

The following example saves a Registry hive to an external file using the Save method:

use Win32::Registry;
$main::HKEY_LOCAL_MACHINE->Open("SOFTWARE", $Software) || 
        die "Open: $!";
$Software->Open("ActiveState", $ActiveState) || 
        die "Open: $!";
# write ActiveState hive to perlkeys.reg
$ActiveState->Save("perlkeys.reg") || 
        die "Save: $!";

You can connect to the Registry of a remote machine (but only to the HKEY_LOCAL_MACHINE or HKEY_USERS hives) using the RegConnectRegistry function:

use Win32::Registry;
Win32::Registry::RegConnectRegistry("\\\\somemachine", 


           HKEY_LOCAL_MACHINE, $key) || die "connect: $!";