Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3440 lines
109 KiB

  1. # Win32/TieRegistry.pm -- Perl module to easily use a Registry
  2. # (on Win32 systems so far).
  3. # by Tye McQueen, [email protected], see http://www.metronet.com/~tye/.
  4. #
  5. # Skip to "=head" line for user documentation.
  6. #
  7. package Win32::TieRegistry;
  8. use strict;
  9. use vars qw( $PACK $VERSION @ISA @EXPORT @EXPORT_OK );
  10. $PACK= "Win32::TieRegistry"; # Used in error messages.
  11. $VERSION= '0.21'; # Released Sept 17, 1998
  12. use Carp;
  13. require Tie::Hash;
  14. @ISA= qw(Tie::Hash);
  15. # Required other modules:
  16. use Win32API::Registry 0.12 qw( :KEY_ :HKEY_ :REG_ );
  17. #Optional other modules:
  18. use vars qw( $_NoMoreItems $_FileNotFound $_TooSmall $_MoreData $_SetDualVar );
  19. if( eval { require Win32::WinError } ) {
  20. $_NoMoreItems= Win32::WinError::constant("ERROR_NO_MORE_ITEMS",0);
  21. $_FileNotFound= Win32::WinError::constant("ERROR_FILE_NOT_FOUND",0);
  22. $_TooSmall= Win32::WinError::constant("ERROR_INSUFFICIENT_BUFFER",0);
  23. $_MoreData= Win32::WinError::constant("ERROR_MORE_DATA",0);
  24. } else {
  25. $_NoMoreItems= "^No more data";
  26. $_FileNotFound= "cannot find the file";
  27. $_TooSmall= " data area passed to ";
  28. $_MoreData= "^more data is avail";
  29. }
  30. if( $_SetDualVar= eval { require SetDualVar } ) {
  31. import SetDualVar;
  32. }
  33. #Implementation details:
  34. # When opened:
  35. # HANDLE long; actual handle value
  36. # MACHINE string; name of remote machine ("" if local)
  37. # PATH list ref; machine-relative full path for this key:
  38. # ["LMachine","System","Disk"]
  39. # ["HKEY_LOCAL_MACHINE","System","Disk"]
  40. # DELIM char; delimiter used to separate subkeys (def="\\")
  41. # OS_DELIM char; always "\\" for Win32
  42. # ACCESS long; usually KEY_ALL_ACCESS, perhaps KEY_READ, etc.
  43. # ROOTS string; var name for "Lmachine"->HKEY_LOCAL_MACHINE map
  44. # FLAGS int; bits to control certain options
  45. # Often:
  46. # VALUES ref to list of value names (data/type never cached)
  47. # SUBKEYS ref to list of subkey names
  48. # SUBCLASSES ref to list of subkey classes
  49. # SUBTIMES ref to list of subkey write times
  50. # MEMBERS ref to list of subkey_name.DELIM's, DELIM.value_name's
  51. # MEMBHASH hash ref to with MEMBERS as keys and 1's as values
  52. # Once Key "Info" requested:
  53. # Class CntSubKeys CntValues MaxSubKeyLen MaxSubClassLen
  54. # MaxValNameLen MaxValDataLen SecurityLen LastWrite
  55. # When tied to a hash and iterating over key values:
  56. # PREVIDX int; index of last MEMBERS element return
  57. # When tied to a hash and iterating over key values:
  58. # UNLOADME list ref; information about Load()ed key
  59. # When a subkey of a "loaded" key:
  60. # DEPENDON obj ref; object that can't be destroyed before us
  61. #Package-local variables:
  62. # Option flag bits:
  63. use vars qw( $Flag_ArrVal $Flag_TieVal $Flag_DualTyp $Flag_DualBin
  64. $Flag_FastDel $Flag_HexDWord $Flag_Split $Flag_FixNulls );
  65. $Flag_ArrVal= 0x0001;
  66. $Flag_TieVal= 0x0002;
  67. $Flag_FastDel= 0x0004;
  68. $Flag_HexDWord= 0x0008;
  69. $Flag_Split= 0x0010;
  70. $Flag_DualTyp= 0x0020;
  71. $Flag_DualBin= 0x0040;
  72. $Flag_FixNulls= 0x0080;
  73. use vars qw( $RegObj %_Roots %RegHash $Registry );
  74. # Short-hand for HKEY_* constants:
  75. %_Roots= (
  76. "Classes" => HKEY_CLASSES_ROOT,
  77. "CUser" => HKEY_CURRENT_USER,
  78. "LMachine" => HKEY_LOCAL_MACHINE,
  79. "Users" => HKEY_USERS,
  80. "PerfData" => HKEY_PERFORMANCE_DATA, # Too picky to be useful
  81. "CConfig" => HKEY_CURRENT_CONFIG,
  82. "DynData" => HKEY_DYN_DATA, # Too picky to be useful
  83. );
  84. # Basic master Registry object:
  85. $RegObj= {};
  86. @$RegObj{qw( HANDLE MACHINE PATH DELIM OS_DELIM ACCESS FLAGS ROOTS )}= (
  87. "NONE", "", [], "\\", "\\",
  88. KEY_READ|KEY_WRITE, $Flag_HexDWord|$Flag_FixNulls, "${PACK}::_Roots" );
  89. $RegObj->{FLAGS} |= $Flag_DualTyp|$Flag_DualBin if $_SetDualVar;
  90. bless $RegObj;
  91. # Fill cache for master Registry object:
  92. @$RegObj{qw( VALUES SUBKEYS SUBCLASSES SUBTIMES )}= (
  93. [], [ keys(%_Roots) ], [], [] );
  94. grep( s#$#$RegObj->{DELIM}#,
  95. @{ $RegObj->{MEMBERS}= [ @{$RegObj->{SUBKEYS}} ] } );
  96. @$RegObj{qw( Class MaxSubKeyLen MaxSubClassLen MaxValNameLen
  97. MaxValDataLen SecurityLen LastWrite CntSubKeys CntValues )}=
  98. ( "", 0, 0, 0, 0, 0, 0, 0, 0 );
  99. # Create master Registry tied hash:
  100. $RegObj->Tie( \%RegHash );
  101. # Create master Registry combination object and tied hash reference:
  102. $Registry= \%RegHash;
  103. bless $Registry;
  104. # Preloaded methods go here.
  105. # Map option names to name of subroutine that controls that option:
  106. use vars qw( @_opt_subs %_opt_subs );
  107. @_opt_subs= qw( Delimiter ArrayValues TieValues SplitMultis DWordsToHex
  108. FastDelete FixSzNulls DualTypes DualBinVals AllowLoad AllowSave );
  109. @_opt_subs{@_opt_subs}= @_opt_subs;
  110. sub import
  111. {
  112. my $pkg= shift(@_);
  113. my $level= $Exporter::ExportLevel;
  114. my $expto= caller($level);
  115. my @export= ();
  116. my @consts= qw( :KEY_ :REG_ );
  117. my $registry= $Registry->Clone;
  118. local( $_ );
  119. while( @_ ) {
  120. $_= shift(@_);
  121. if( /^\$(\w+::)*\w+$/ ) {
  122. push( @export, "ObjVar" ) if /^\$RegObj$/;
  123. push( @export, $_ );
  124. } elsif( /^\%(\w+::)*\w+$/ ) {
  125. push( @export, $_ );
  126. } elsif( /^[$%]/ ) {
  127. croak "${PACK}->import: Invalid variable name ($_)";
  128. } elsif( /^:/ || /^(H?KEY|REG)_/ ) {
  129. Win32API::Registry->export( $expto, $_ )
  130. unless /^:$/;
  131. @consts= ();
  132. } elsif( ! @_ ) {
  133. croak "${PACK}->import: Missing argument after option ($_)";
  134. } elsif( exists $_opt_subs{$_} ) {
  135. $_= $_opt_subs{$_};
  136. $registry->$_( shift(@_) );
  137. } elsif( /^TiedRef$/ ) {
  138. $_= shift(@_);
  139. if( ! ref($_) && /^(\$?)(\w+::)*\w+$/ ) {
  140. $_= '$'.$_ unless '$' eq $1;
  141. } elsif( "SCALAR" ne ref($_) ) {
  142. croak "${PACK}->import: Invalid var after TiedRef ($_)";
  143. }
  144. push( @export, $_ );
  145. } elsif( /^TiedHash$/ ) {
  146. $_= shift(@_);
  147. if( ! ref($_) && /^(\%?)(\w+::)*\w+$/ ) {
  148. $_= '%'.$_ unless '%' eq $1;
  149. } elsif( "HASH" ne ref($_) ) {
  150. croak "${PACK}->import: Invalid var after TiedHash ($_)";
  151. }
  152. push( @export, $_ );
  153. } elsif( /^ObjectRef$/ ) {
  154. $_= shift(@_);
  155. if( ! ref($_) && /^(\$?)(\w+::)*\w+$/ ) {
  156. push( @export, "ObjVar" );
  157. $_= '$'.$_ unless '$' eq $1;
  158. } elsif( "SCALAR" eq ref($_) ) {
  159. push( @export, "ObjRef" );
  160. } else {
  161. croak "${PACK}->import: Invalid var after ObjectRef ($_)";
  162. }
  163. push( @export, $_ );
  164. } elsif( /^ExportLevel$/ ) {
  165. $level= shift(@_);
  166. $expto= caller($level);
  167. } elsif( /^ExportTo$/ ) {
  168. undef $level;
  169. $expto= caller($level);
  170. } else {
  171. croak "${PACK}->import: Invalid option ($_)";
  172. }
  173. }
  174. @export= ('$Registry') unless @export;
  175. while( @export ) {
  176. $_= shift( @export );
  177. if( /^\$((?:\w+::)*)(\w+)$/ ) {
  178. my( $pack, $sym )= ( $1, $2 );
  179. $pack= $expto unless defined($pack) && "" ne $pack;
  180. no strict 'refs';
  181. *{"${pack}::$sym"}= \${"${pack}::$sym"};
  182. ${"${pack}::$sym"}= $registry;
  183. } elsif( /^\%((?:\w+::)*)(\w+)$/ ) {
  184. my( $pack, $sym )= ( $1, $2 );
  185. $pack= $expto unless defined($pack) && "" ne $pack;
  186. no strict 'refs';
  187. *{"${pack}::$sym"}= \%{"${pack}::$sym"};
  188. $registry->Tie( \%{"${pack}::$sym"} );
  189. } elsif( "SCALAR" eq ref($_) ) {
  190. $$_= $registry;
  191. } elsif( "HASH" eq ref($_) ) {
  192. $registry->Tie( $_ );
  193. } elsif( /^ObjVar$/ ) {
  194. $_= shift( @_ );
  195. /^\$((?:\w+::)*)(\w+)$/;
  196. my( $pack, $sym )= ( $1, $2 );
  197. $pack= $expto unless defined($pack) && "" ne $pack;
  198. no strict 'refs';
  199. *{"${pack}::$sym"}= \${"${pack}::$sym"};
  200. ${"${pack}::$sym"}= $registry->ObjectRef;
  201. } elsif( /^ObjRef$/ ) {
  202. ${shift(@_)}= $registry->ObjectRef;
  203. } else {
  204. die "Impossible var to export ($_)";
  205. }
  206. }
  207. }
  208. use vars qw( @_new_Opts %_new_Opts );
  209. @_new_Opts= qw( ACCESS DELIM MACHINE DEPENDON );
  210. @_new_Opts{@_new_Opts}= (1) x @_new_Opts;
  211. sub _new
  212. {
  213. my $this= shift( @_ );
  214. $this= tied(%$this) if ref($this) && tied(%$this);
  215. my $class= ref($this) || $this;
  216. my $self= {};
  217. my( $handle, $rpath, $opts )= @_;
  218. if( @_ < 2 || "ARRAY" ne ref($rpath) || 3 < @_
  219. || 3 == @_ && "HASH" ne ref($opts) ) {
  220. croak "Usage: ${PACK}->_new( \$handle, \\\@path, {OPT=>VAL,...} );\n",
  221. " options: @_new_Opts\nCalled";
  222. }
  223. @$self{qw( HANDLE PATH )}= ( $handle, $rpath );
  224. @$self{qw( MACHINE ACCESS DELIM OS_DELIM ROOTS FLAGS )}=
  225. ( $this->Machine, $this->Access, $this->Delimiter,
  226. $this->OS_Delimiter, $this->_Roots, $this->_Flags );
  227. if( ref($opts) ) {
  228. my @err= grep( ! $_new_Opts{$_}, keys(%$opts) );
  229. @err and croak "${PACK}->_new: Invalid options (@err)";
  230. @$self{ keys(%$opts) }= values(%$opts);
  231. }
  232. bless $self, $class;
  233. return $self;
  234. }
  235. sub _split
  236. {
  237. my $self= shift( @_ );
  238. $self= tied(%$self) if tied(%$self);
  239. my $path= shift( @_ );
  240. my $delim= @_ ? shift(@_) : $self->Delimiter;
  241. my $list= [ split( /\Q$delim/, $path ) ];
  242. $list;
  243. }
  244. sub _rootKey
  245. {
  246. my $self= shift(@_);
  247. $self= tied(%$self) if tied(%$self);
  248. my $keyPath= shift(@_);
  249. my $delim= @_ ? shift(@_) : $self->Delimiter;
  250. my( $root, $subPath );
  251. if( "ARRAY" eq ref($keyPath) ) {
  252. $subPath= $keyPath;
  253. } else {
  254. $subPath= $self->_split( $keyPath, $delim );
  255. }
  256. $root= shift( @$subPath );
  257. if( $root =~ /^HKEY_/ ) {
  258. my $handle= Win32API::Registry::constant($root,0);
  259. $handle or croak "Invalid HKEY_ constant ($root): $!";
  260. return( $self->_new( $handle, [$root], {DELIM=>$delim} ),
  261. $subPath );
  262. } elsif( $root =~ /^([-+]|0x)?\d/ ) {
  263. return( $self->_new( $root, [sprintf("0x%lX",$root)],
  264. {DELIM=>$delim} ),
  265. $subPath );
  266. } else {
  267. my $roots= $self->Roots;
  268. if( $roots->{$root} ) {
  269. return( $self->_new( $roots->{$root}, [$root], {DELIM=>$delim} ),
  270. $subPath );
  271. }
  272. croak "No such root key ($root)";
  273. }
  274. }
  275. sub _open
  276. {
  277. my $this= shift(@_);
  278. $this= tied(%$this) if ref($this) && tied(%$this);
  279. my $subPath= shift(@_);
  280. my $sam= @_ ? shift(@_) : $this->Access;
  281. my $subKey= join( $this->OS_Delimiter, @$subPath );
  282. my $handle= 0;
  283. $this->RegOpenKeyEx( $subKey, 0, $sam, $handle )
  284. or return wantarray ? () : undef;
  285. return $this->_new( $handle, [ @{$this->_Path}, @$subPath ],
  286. { ACCESS=>$sam, ( defined($this->{UNLOADME}) ? ("DEPENDON",$this)
  287. : defined($this->{DEPENDON}) ? ("DEPENDON",$this->{DEPENDON}) : () )
  288. } );
  289. }
  290. sub ObjectRef
  291. {
  292. my $self= shift(@_);
  293. $self= tied(%$self) if tied(%$self);
  294. $self;
  295. }
  296. sub _connect
  297. {
  298. my $this= shift(@_);
  299. $this= tied(%$this) if ref($this) && tied(%$this);
  300. my $subPath= pop(@_);
  301. $subPath= $this->_split( $subPath ) unless ref($subPath);
  302. my $machine= @_ ? shift(@_) : shift(@$subPath);
  303. my $handle= 0;
  304. my( $temp )= $this->_rootKey( [@$subPath] );
  305. $temp->RegConnectRegistry( $machine, $temp->Handle, $handle )
  306. or return wantarray ? () : undef;
  307. my $self= $this->_new( $handle, [shift(@$subPath)], {MACHINE=>$machine} );
  308. ( $self, $subPath );
  309. }
  310. use vars qw( @Connect_Opts %Connect_Opts );
  311. @Connect_Opts= qw(Access Delimiter);
  312. @Connect_Opts{@Connect_Opts}= (1) x @Connect_Opts;
  313. sub Connect
  314. {
  315. my $this= shift(@_);
  316. my $tied= ref($this) && tied(%$this);
  317. $this= tied(%$this) if $tied;
  318. my( $machine, $key, $opts )= @_;
  319. my $delim= "";
  320. my $sam;
  321. my $subPath;
  322. if( @_ < 2 || 3 < @_
  323. || 3 == @_ && "HASH" ne ref($opts) ) {
  324. croak "Usage: \$obj= ${PACK}->Connect(",
  325. " \$Machine, \$subKey, { OPT=>VAL,... } );\n",
  326. " options: @Connect_Opts\nCalled";
  327. }
  328. if( ref($opts) ) {
  329. my @err= grep( ! $Connect_Opts{$_}, keys(%$opts) );
  330. @err and croak "${PACK}->Connect: Invalid options (@err)";
  331. }
  332. $delim= "$opts->{Delimiter}" if defined($opts->{Delimiter});
  333. $delim= $this->Delimiter if "" eq $delim;
  334. $sam= defined($opts->{Access}) ? $opts->{Access} : $this->Access;
  335. $sam= Win32API::Registry::constant($sam,0) if $sam =~ /^KEY_/;
  336. ( $this, $subPath )= $this->_connect( $machine, $key );
  337. return wantarray ? () : undef unless defined($this);
  338. my $self= $this->_open( $subPath, $sam );
  339. return wantarray ? () : undef unless defined($self);
  340. $self->Delimiter( $delim );
  341. $self= $self->TiedRef if $tied;
  342. return $self;
  343. }
  344. my @_newVirtual_keys= qw( MEMBERS VALUES SUBKEYS SUBTIMES SUBCLASSES
  345. Class SecurityLen LastWrite CntValues CntSubKeys
  346. MaxValNameLen MaxValDataLen MaxSubKeyLen MaxSubClassLen );
  347. sub _newVirtual
  348. {
  349. my $self= shift(@_);
  350. my( $rPath, $root, $opts )= @_;
  351. my $new= $self->_new( "NONE", $rPath, $opts )
  352. or return wantarray ? () : undef;
  353. @{$new}{@_newVirtual_keys}= @{$root->ObjectRef}{@_newVirtual_keys};
  354. return $new;
  355. }
  356. #$key= new Win32::TieRegistry "LMachine/System/Disk";
  357. #$key= new Win32::TieRegistry "//Server1/LMachine/System/Disk";
  358. #Win32::TieRegistry->new( HKEY_LOCAL_MACHINE, {DELIM=>"/",ACCESS=>KEY_READ} );
  359. #Win32::TieRegistry->new( [ HKEY_LOCAL_MACHINE, ".../..." ], {DELIM=>$DELIM} );
  360. #$key->new( ... );
  361. use vars qw( @new_Opts %new_Opts );
  362. @new_Opts= qw(Access Delimiter);
  363. @new_Opts{@new_Opts}= (1) x @new_Opts;
  364. sub new
  365. {
  366. my $this= shift( @_ );
  367. $this= tied(%$this) if ref($this) && tied(%$this);
  368. my( $subKey, $opts )= @_;
  369. my $delim= "";
  370. my $dlen;
  371. my $sam;
  372. my $subPath;
  373. if( @_ < 1 || 2 < @_
  374. || 2 == @_ && "HASH" ne ref($opts) ) {
  375. croak "Usage: \$obj= ${PACK}->new( \$subKey, { OPT=>VAL,... } );\n",
  376. " options: @new_Opts\nCalled";
  377. }
  378. if( defined($opts) ) {
  379. my @err= grep( ! $new_Opts{$_}, keys(%$opts) );
  380. @err and die "${PACK}->new: Invalid options (@err)";
  381. }
  382. $delim= "$opts->{Delimiter}" if defined($opts->{Delimiter});
  383. $delim= $this->Delimiter if "" eq $delim;
  384. $dlen= length($delim);
  385. $sam= defined($opts->{Access}) ? $opts->{Access} : $this->Access;
  386. $sam= Win32API::Registry::constant($sam,0) if $sam =~ /^KEY_/;
  387. if( "ARRAY" eq ref($subKey) ) {
  388. $subPath= $subKey;
  389. if( "NONE" eq $this->Handle && @$subPath ) {
  390. ( $this, $subPath )= $this->_rootKey( $subPath );
  391. }
  392. } elsif( $delim x 2 eq substr($subKey,0,2*$dlen) ) {
  393. my $path= $this->_split( substr($subKey,2*$dlen), $delim );
  394. my $mach= shift(@$path);
  395. if( ! @$path ) {
  396. return $this->_newVirtual( $path, $Registry,
  397. {MACHINE=>$mach,DELIM=>$delim,ACCESS=>$sam} );
  398. }
  399. ( $this, $subPath )= $this->_connect( $mach, $path );
  400. return wantarray ? () : undef if ! defined($this);
  401. if( 0 == @$subPath ) {
  402. $this->Delimiter( $delim );
  403. return $this;
  404. }
  405. } elsif( $delim eq substr($subKey,0,$dlen) ) {
  406. ( $this, $subPath )= $this->_rootKey( substr($subKey,$dlen), $delim );
  407. } elsif( "NONE" eq $this->Handle && "" ne $subKey ) {
  408. my( $mach )= $this->Machine;
  409. if( $mach ) {
  410. ( $this, $subPath )= $this->_connect( $mach, $subKey );
  411. } else {
  412. ( $this, $subPath )= $this->_rootKey( $subKey, $delim );
  413. }
  414. } else {
  415. $subPath= $this->_split( $subKey, $delim );
  416. }
  417. return wantarray ? () : undef unless defined($this);
  418. if( 0 == @$subPath && "NONE" eq $this->Handle ) {
  419. return $this->_newVirtual( $this->_Path, $this,
  420. { DELIM=>$delim, ACCESS=>$sam } );
  421. }
  422. my $self= $this->_open( $subPath, $sam );
  423. return wantarray ? () : undef unless defined($self);
  424. $self->Delimiter( $delim );
  425. return $self;
  426. }
  427. sub Open
  428. {
  429. my $self= shift(@_);
  430. my $tied= ref($self) && tied(%$self);
  431. $self= tied(%$self) if $tied;
  432. $self= $self->new( @_ );
  433. $self= $self->TiedRef if defined($self) && $tied;
  434. return $self;
  435. }
  436. sub Clone
  437. {
  438. my $self= shift( @_ );
  439. my $new= $self->Open("");
  440. return $new;
  441. }
  442. { my @flush;
  443. sub Flush
  444. {
  445. my $self= shift(@_);
  446. $self= tied(%$self) if tied(%$self);
  447. my( $flush )= @_;
  448. @_ and croak "Usage: \$key->Flush( \$bFlush );";
  449. return 0 if "NONE" eq $self->Handle;
  450. @flush= qw( VALUES SUBKEYS SUBCLASSES SUBTIMES MEMBERS Class
  451. CntSubKeys CntValues MaxSubKeyLen MaxSubClassLen
  452. MaxValNameLen MaxValDataLen SecurityLen LastWrite PREVIDX )
  453. unless @flush;
  454. delete( @$self{@flush} );
  455. if( defined($flush) && $flush ) {
  456. return $self->RegFlushKey();
  457. } else {
  458. return 1;
  459. }
  460. }
  461. }
  462. sub _DualVal
  463. {
  464. my( $hRef, $num )= @_;
  465. if( $_SetDualVar && $$hRef{$num} ) {
  466. &SetDualVar( $num, "$$hRef{$num}", 0+$num );
  467. }
  468. $num;
  469. }
  470. use vars qw( @_RegDataTypes %_RegDataTypes );
  471. @_RegDataTypes= qw( REG_NONE REG_SZ REG_EXPAND_SZ REG_BINARY
  472. REG_DWORD_LITTLE_ENDIAN REG_DWORD_BIG_ENDIAN
  473. REG_DWORD REG_LINK REG_MULTI_SZ REG_RESOURCE_LIST
  474. REG_FULL_RESOURCE_DESCRIPTOR
  475. REG_RESOURCE_REQUIREMENTS_LIST );
  476. # Make sure REG_DWORD appears _after_ other REG_DWORD_* items above.
  477. foreach( @_RegDataTypes ) {
  478. $_RegDataTypes{Win32API::Registry::constant($_,0)}= $_;
  479. }
  480. sub GetValue
  481. {
  482. my $self= shift(@_);
  483. $self= tied(%$self) if tied(%$self);
  484. 1 == @_ or croak "Usage: (\$data,\$type)= \$key->GetValue('ValName');";
  485. my( $valName )= @_;
  486. my( $valType, $valData, $dLen )= (0,"",0);
  487. return wantarray ? () : undef if "NONE" eq $self->Handle;
  488. $self->RegQueryValueEx( $valName, [], $valType, $valData,
  489. $dLen= ( defined($self->{MaxValDataLen}) ? $self->{MaxValDataLen} : 0 )
  490. ) or return wantarray ? () : undef;
  491. if( REG_DWORD == $valType ) {
  492. my $val= unpack("L",$valData);
  493. $valData= sprintf "0x%08.8lX", $val if $self->DWordsToHex;
  494. &SetDualVar( $valData, $valData, $val ) if $self->DualBinVals
  495. } elsif( REG_BINARY == $valType && length($valData) <= 4 ) {
  496. &SetDualVar( $valData, $valData, hex reverse unpack("h*",$valData) )
  497. if $self->DualBinVals;
  498. } elsif( ( REG_SZ == $valType || REG_EXPAND_SZ == $valType )
  499. && $self->FixSzNulls ) {
  500. substr($valData,-1)= "" if "\0" eq substr($valData,-1);
  501. } elsif( REG_MULTI_SZ == $valType && $self->SplitMultis ) {
  502. ## $valData =~ s/\0\0$//; # Why does this often fail??
  503. substr($valData,-2)= "" if "\0\0" eq substr($valData,-2);
  504. $valData= [ split( /\0/, $valData, -1 ) ]
  505. }
  506. if( ! wantarray ) {
  507. return $valData;
  508. } elsif( ! $self->DualTypes ) {
  509. return( $valData, $valType );
  510. } else {
  511. return( $valData, _DualVal( \%_RegDataTypes, $valType ) );
  512. }
  513. }
  514. sub _ErrNum
  515. {
  516. # return $^E;
  517. return Win32::GetLastError();
  518. }
  519. sub _ErrMsg
  520. {
  521. # return $^E;
  522. return Win32::FormatMessage( Win32::GetLastError() );
  523. }
  524. sub _Err
  525. {
  526. my $err;
  527. # return $^E;
  528. return _ErrMsg if ! $_SetDualVar;
  529. return &SetDualVar( $err, _ErrMsg, _ErrNum );
  530. }
  531. sub _NoMoreItems
  532. {
  533. $_NoMoreItems =~ /^\d/
  534. ? _ErrNum == $_NoMoreItems
  535. : _ErrMsg =~ /$_NoMoreItems/io;
  536. }
  537. sub _FileNotFound
  538. {
  539. $_FileNotFound =~ /^\d/
  540. ? _ErrNum == $_FileNotFound
  541. : _ErrMsg =~ /$_FileNotFound/io;
  542. }
  543. sub _TooSmall
  544. {
  545. $_TooSmall =~ /^\d/
  546. ? _ErrNum == $_TooSmall
  547. : _ErrMsg =~ /$_TooSmall/io;
  548. }
  549. sub _MoreData
  550. {
  551. $_MoreData =~ /^\d/
  552. ? _ErrNum == $_MoreData
  553. : _ErrMsg =~ /$_MoreData/io;
  554. }
  555. sub _enumValues
  556. {
  557. my $self= shift(@_);
  558. $self= tied(%$self) if tied(%$self);
  559. my( @names )= ();
  560. my $pos= 0;
  561. my $name= "";
  562. my $nlen= 1+$self->Information("MaxValNameLen");
  563. while( $self->RegEnumValue($pos++,$name,$nlen,[],[],[],[]) ) {
  564. push( @names, $name );
  565. }
  566. if( ! _NoMoreItems() ) {
  567. return wantarray ? () : undef;
  568. }
  569. $self->{VALUES}= \@names;
  570. 1;
  571. }
  572. sub ValueNames
  573. {
  574. my $self= shift(@_);
  575. $self= tied(%$self) if tied(%$self);
  576. @_ and croak "Usage: \@names= \$key->ValueNames;";
  577. $self->_enumValues unless $self->{VALUES};
  578. return @{$self->{VALUES}};
  579. }
  580. sub _enumSubKeys
  581. {
  582. my $self= shift(@_);
  583. $self= tied(%$self) if tied(%$self);
  584. my( @subkeys, @classes, @times )= ();
  585. my $pos= 0;
  586. my( $subkey, $class, $time )= ("","","");
  587. my( $namSiz, $clsSiz )= $self->Information(
  588. qw( MaxSubKeyLen MaxSubClassLen ));
  589. $namSiz++; $clsSiz++;
  590. while( $self->RegEnumKeyEx(
  591. $pos++, $subkey, $namSiz, [], $class, $clsSiz, $time ) ) {
  592. push( @subkeys, $subkey );
  593. push( @classes, $class );
  594. push( @times, $time );
  595. }
  596. if( ! _NoMoreItems() ) {
  597. return wantarray ? () : undef;
  598. }
  599. $self->{SUBKEYS}= \@subkeys;
  600. $self->{SUBCLASSES}= \@classes;
  601. $self->{SUBTIMES}= \@times;
  602. 1;
  603. }
  604. sub SubKeyNames
  605. {
  606. my $self= shift(@_);
  607. $self= tied(%$self) if tied(%$self);
  608. @_ and croak "Usage: \@names= \$key->SubKeyNames;";
  609. $self->_enumSubKeys unless $self->{SUBKEYS};
  610. return @{$self->{SUBKEYS}};
  611. }
  612. sub SubKeyClasses
  613. {
  614. my $self= shift(@_);
  615. @_ and croak "Usage: \@classes= \$key->SubKeyClasses;";
  616. $self->_enumSubKeys unless $self->{SUBCLASSES};
  617. return @{$self->{SUBCLASSES}};
  618. }
  619. sub SubKeyTimes
  620. {
  621. my $self= shift(@_);
  622. $self= tied(%$self) if tied(%$self);
  623. @_ and croak "Usage: \@times= \$key->SubKeyTimes;";
  624. $self->_enumSubKeys unless $self->{SUBTIMES};
  625. return @{$self->{SUBTIMES}};
  626. }
  627. sub _MemberNames
  628. {
  629. my $self= shift(@_);
  630. $self= tied(%$self) if tied(%$self);
  631. @_ and croak "Usage: \$arrayRef= \$key->_MemberNames;";
  632. if( ! $self->{MEMBERS} ) {
  633. $self->_enumValues unless $self->{VALUES};
  634. $self->_enumSubKeys unless $self->{SUBKEYS};
  635. my( @members )= ( map( $_.$self->{DELIM}, @{$self->{SUBKEYS}} ),
  636. map( $self->{DELIM}.$_, @{$self->{VALUES}} ) );
  637. $self->{MEMBERS}= \@members;
  638. }
  639. return $self->{MEMBERS};
  640. }
  641. sub _MembersHash
  642. {
  643. my $self= shift(@_);
  644. $self= tied(%$self) if tied(%$self);
  645. @_ and croak "Usage: \$hashRef= \$key->_MembersHash;";
  646. if( ! $self->{MEMBHASH} ) {
  647. my $aRef= $self->_MemberNames;
  648. $self->{MEMBHASH}= {};
  649. @{$self->{MEMBHASH}}{@$aRef}= (1) x @$aRef;
  650. }
  651. return $self->{MEMBHASH};
  652. }
  653. sub MemberNames
  654. {
  655. my $self= shift(@_);
  656. $self= tied(%$self) if tied(%$self);
  657. @_ and croak "Usage: \@members= \$key->MemberNames;";
  658. return @{$self->_MemberNames};
  659. }
  660. sub Information
  661. {
  662. my $self= shift(@_);
  663. $self= tied(%$self) if tied(%$self);
  664. my( $time, $nkeys, $nvals, $xsec, $xkey, $xcls, $xname, $xdata )=
  665. ("",0,0,0,0,0,0,0);
  666. my $clen= 8;
  667. if( ! $self->RegQueryInfoKey( [], [], $nkeys, $xkey, $xcls,
  668. $nvals, $xname, $xdata, $xsec, $time ) ) {
  669. return wantarray ? () : undef;
  670. }
  671. if( defined($self->{Class}) ) {
  672. $clen= length($self->{Class});
  673. } else {
  674. $self->{Class}= "";
  675. }
  676. while( ! $self->RegQueryInfoKey( $self->{Class}, $clen,
  677. [],[],[],[],[],[],[],[],[])
  678. && _MoreData ) {
  679. $clen *= 2;
  680. }
  681. my( %info );
  682. @info{ qw( LastWrite CntSubKeys CntValues SecurityLen
  683. MaxValDataLen MaxSubKeyLen MaxSubClassLen MaxValNameLen )
  684. }= ( $time, $nkeys, $nvals, $xsec,
  685. $xdata, $xkey, $xcls, $xname );
  686. if( @_ ) {
  687. my( %check );
  688. @check{keys(%info)}= keys(%info);
  689. my( @err )= grep( ! $check{$_}, @_ );
  690. if( @err ) {
  691. croak "${PACK}::Information- Invalid info requested (@err)";
  692. }
  693. return @info{@_};
  694. } else {
  695. return %info;
  696. }
  697. }
  698. sub Delimiter
  699. {
  700. my $self= shift(@_);
  701. $self= tied(%$self) if tied(%$self);
  702. $self= $RegObj unless ref($self);
  703. my( $oldDelim )= $self->{DELIM};
  704. if( 1 == @_ && "" ne "$_[0]" ) {
  705. delete $self->{MEMBERS};
  706. delete $self->{MEMBHASH};
  707. $self->{DELIM}= "$_[0]";
  708. } elsif( 0 != @_ ) {
  709. croak "Usage: \$oldDelim= \$key->Delimiter(\$newDelim);";
  710. }
  711. $oldDelim;
  712. }
  713. sub Handle
  714. {
  715. my $self= shift(@_);
  716. $self= tied(%$self) if tied(%$self);
  717. @_ and croak "Usage: \$handle= \$key->Handle;";
  718. $self= $RegObj unless ref($self);
  719. $self->{HANDLE};
  720. }
  721. sub Path
  722. {
  723. my $self= shift(@_);
  724. $self= tied(%$self) if tied(%$self);
  725. @_ and croak "Usage: \$path= \$key->Path;";
  726. my $delim= $self->{DELIM};
  727. $self= $RegObj unless ref($self);
  728. if( "" eq $self->{MACHINE} ) {
  729. $delim . join( $delim, @{$self->{PATH}} ) . $delim;
  730. } else {
  731. $delim x 2
  732. . join( $delim, $self->{MACHINE}, @{$self->{PATH}} )
  733. . $delim;
  734. }
  735. }
  736. sub _Path
  737. {
  738. my $self= shift(@_);
  739. $self= tied(%$self) if tied(%$self);
  740. @_ and croak "Usage: \$arrRef= \$key->_Path;";
  741. $self= $RegObj unless ref($self);
  742. $self->{PATH};
  743. }
  744. sub Machine
  745. {
  746. my $self= shift(@_);
  747. $self= tied(%$self) if tied(%$self);
  748. @_ and croak "Usage: \$machine= \$key->Machine;";
  749. $self= $RegObj unless ref($self);
  750. $self->{MACHINE};
  751. }
  752. sub Access
  753. {
  754. my $self= shift(@_);
  755. $self= tied(%$self) if tied(%$self);
  756. @_ and croak "Usage: \$access= \$key->Access;";
  757. $self= $RegObj unless ref($self);
  758. $self->{ACCESS};
  759. }
  760. sub OS_Delimiter
  761. {
  762. my $self= shift(@_);
  763. @_ and croak "Usage: \$backslash= \$key->OS_Delimiter;";
  764. $self->{OS_DELIM};
  765. }
  766. sub _Roots
  767. {
  768. my $self= shift(@_);
  769. $self= tied(%$self) if ref($self) && tied(%$self);
  770. @_ and croak "Usage: \$varName= \$key->_Roots;";
  771. $self= $RegObj unless ref($self);
  772. $self->{ROOTS};
  773. }
  774. sub Roots
  775. {
  776. my $self= shift(@_);
  777. $self= tied(%$self) if ref($self) && tied(%$self);
  778. @_ and croak "Usage: \$hashRef= \$key->Roots;";
  779. $self= $RegObj unless ref($self);
  780. eval "\\%$self->{ROOTS}";
  781. }
  782. sub TIEHASH
  783. {
  784. my( $this )= shift(@_);
  785. $this= tied(%$this) if ref($this) && tied(%$this);
  786. my( $key )= @_;
  787. if( 1 == @_ && ref($key) && "$key" =~ /=/ ) {
  788. return $key; # $key is already an object (blessed reference).
  789. }
  790. return $this->new( @_ );
  791. }
  792. sub Tie
  793. {
  794. my $self= shift(@_);
  795. $self= tied(%$self) if tied(%$self);
  796. my( $hRef )= @_;
  797. if( 1 != @_ || ! ref($hRef) || "$hRef" !~ /(^|=)HASH\(/ ) {
  798. croak "Usage: \$key->Tie(\\\%hash);";
  799. }
  800. tie %$hRef, ref($self), $self;
  801. }
  802. sub TiedRef
  803. {
  804. my $self= shift(@_);
  805. $self= tied(%$self) if tied(%$self);
  806. my $hRef= @_ ? shift(@_) : {};
  807. return wantarray ? () : undef if ! defined($self);
  808. $self->Tie($hRef);
  809. bless $hRef, ref($self);
  810. $hRef;
  811. }
  812. sub _Flags
  813. {
  814. my $self= shift(@_);
  815. $self= tied(%$self) if tied(%$self);
  816. my $oldFlags= $self->{FLAGS};
  817. if( 1 == @_ ) {
  818. $self->{FLAGS}= shift(@_);
  819. } elsif( 0 != @_ ) {
  820. croak "Usage: \$oldBits= \$key->_Flags(\$newBits);";
  821. }
  822. $oldFlags;
  823. }
  824. sub ArrayValues
  825. {
  826. my $self= shift(@_);
  827. $self= tied(%$self) if tied(%$self);
  828. my $oldFlag= $Flag_ArrVal == ( $Flag_ArrVal & $self->{FLAGS} );
  829. if( 1 == @_ ) {
  830. my $bool= shift(@_);
  831. if( $bool ) {
  832. $self->{FLAGS} |= $Flag_ArrVal;
  833. } else {
  834. $self->{FLAGS} &= ~( $Flag_ArrVal | $Flag_TieVal );
  835. }
  836. } elsif( 0 != @_ ) {
  837. croak "Usage: \$oldBool= \$key->ArrayValues(\$newBool);";
  838. }
  839. $oldFlag;
  840. }
  841. sub TieValues
  842. {
  843. my $self= shift(@_);
  844. $self= tied(%$self) if tied(%$self);
  845. my $oldFlag= $Flag_TieVal == ( $Flag_TieVal & $self->{FLAGS} );
  846. if( 1 == @_ ) {
  847. my $bool= shift(@_);
  848. if( $bool ) {
  849. croak "${PACK}->TieValues cannot be enabled with this version";
  850. $self->{FLAGS} |= $Flag_TieVal;
  851. } else {
  852. $self->{FLAGS} &= ~$Flag_TieVal;
  853. }
  854. } elsif( 0 != @_ ) {
  855. croak "Usage: \$oldBool= \$key->TieValues(\$newBool);";
  856. }
  857. $oldFlag;
  858. }
  859. sub FastDelete
  860. {
  861. my $self= shift(@_);
  862. $self= tied(%$self) if tied(%$self);
  863. my $oldFlag= $Flag_FastDel == ( $Flag_FastDel & $self->{FLAGS} );
  864. if( 1 == @_ ) {
  865. my $bool= shift(@_);
  866. if( $bool ) {
  867. $self->{FLAGS} |= $Flag_FastDel;
  868. } else {
  869. $self->{FLAGS} &= ~$Flag_FastDel;
  870. }
  871. } elsif( 0 != @_ ) {
  872. croak "Usage: \$oldBool= \$key->FastDelete(\$newBool);";
  873. }
  874. $oldFlag;
  875. }
  876. sub SplitMultis
  877. {
  878. my $self= shift(@_);
  879. $self= tied(%$self) if tied(%$self);
  880. my $oldFlag= $Flag_Split == ( $Flag_Split & $self->{FLAGS} );
  881. if( 1 == @_ ) {
  882. my $bool= shift(@_);
  883. if( $bool ) {
  884. $self->{FLAGS} |= $Flag_Split;
  885. } else {
  886. $self->{FLAGS} &= ~$Flag_Split;
  887. }
  888. } elsif( 0 != @_ ) {
  889. croak "Usage: \$oldBool= \$key->SplitMultis(\$newBool);";
  890. }
  891. $oldFlag;
  892. }
  893. sub DWordsToHex
  894. {
  895. my $self= shift(@_);
  896. $self= tied(%$self) if tied(%$self);
  897. my $oldFlag= $Flag_HexDWord == ( $Flag_HexDWord & $self->{FLAGS} );
  898. if( 1 == @_ ) {
  899. my $bool= shift(@_);
  900. if( $bool ) {
  901. $self->{FLAGS} |= $Flag_HexDWord;
  902. } else {
  903. $self->{FLAGS} &= ~$Flag_HexDWord;
  904. }
  905. } elsif( 0 != @_ ) {
  906. croak "Usage: \$oldBool= \$key->DWordsToHex(\$newBool);";
  907. }
  908. $oldFlag;
  909. }
  910. sub FixSzNulls
  911. {
  912. my $self= shift(@_);
  913. $self= tied(%$self) if tied(%$self);
  914. my $oldFlag= $Flag_FixNulls == ( $Flag_FixNulls & $self->{FLAGS} );
  915. if( 1 == @_ ) {
  916. my $bool= shift(@_);
  917. if( $bool ) {
  918. $self->{FLAGS} |= $Flag_FixNulls;
  919. } else {
  920. $self->{FLAGS} &= ~$Flag_FixNulls;
  921. }
  922. } elsif( 0 != @_ ) {
  923. croak "Usage: \$oldBool= \$key->FixSzNulls(\$newBool);";
  924. }
  925. $oldFlag;
  926. }
  927. sub DualTypes
  928. {
  929. my $self= shift(@_);
  930. $self= tied(%$self) if tied(%$self);
  931. my $oldFlag= $Flag_DualTyp == ( $Flag_DualTyp & $self->{FLAGS} );
  932. if( 1 == @_ ) {
  933. my $bool= shift(@_);
  934. if( $bool ) {
  935. croak "${PACK}->DualTypes cannot be enabled since ",
  936. "SetDualVar module not installed"
  937. unless $_SetDualVar;
  938. $self->{FLAGS} |= $Flag_DualTyp;
  939. } else {
  940. $self->{FLAGS} &= ~$Flag_DualTyp;
  941. }
  942. } elsif( 0 != @_ ) {
  943. croak "Usage: \$oldBool= \$key->DualTypes(\$newBool);";
  944. }
  945. $oldFlag;
  946. }
  947. sub DualBinVals
  948. {
  949. my $self= shift(@_);
  950. $self= tied(%$self) if tied(%$self);
  951. my $oldFlag= $Flag_DualBin == ( $Flag_DualBin & $self->{FLAGS} );
  952. if( 1 == @_ ) {
  953. my $bool= shift(@_);
  954. if( $bool ) {
  955. croak "${PACK}->DualBinVals cannot be enabled since ",
  956. "SetDualVar module not installed"
  957. unless $_SetDualVar;
  958. $self->{FLAGS} |= $Flag_DualBin;
  959. } else {
  960. $self->{FLAGS} &= ~$Flag_DualBin;
  961. }
  962. } elsif( 0 != @_ ) {
  963. croak "Usage: \$oldBool= \$key->DualBinVals(\$newBool);";
  964. }
  965. $oldFlag;
  966. }
  967. sub GetOptions
  968. {
  969. my $self= shift(@_);
  970. $self= tied(%$self) if tied(%$self);
  971. my( $opt, $meth, @old );
  972. foreach $opt ( @_ ) {
  973. $meth= $_opt_subs{$opt};
  974. if( defined $meth ) {
  975. if( $opt eq "AllowLoad" || $opt eq "AllowSave" ) {
  976. croak "${PACK}->GetOptions: Getting current setting of $opt ",
  977. "not supported in this release";
  978. }
  979. push( @old, $self->$meth() );
  980. } else {
  981. croak "${PACK}->GetOptions: Invalid option ($opt) ",
  982. "not one of ( ", join(" ",grep !/^Allow/, @_opt_subs), " )";
  983. }
  984. }
  985. return wantarray ? @old : $old[-1];
  986. }
  987. sub SetOptions
  988. {
  989. my $self= shift(@_);
  990. # Don't get object if hash ref so "ref" returns original ref.
  991. my( $opt, $meth, @old );
  992. while( @_ ) {
  993. $opt= shift(@_);
  994. $meth= $_opt_subs{$opt};
  995. if( ! @_ ) {
  996. croak "${PACK}->SetOptions: Option value missing ",
  997. "after option name ($opt)";
  998. } elsif( defined $meth ) {
  999. push( @old, $self->$meth( shift(@_) ) );
  1000. } elsif( $opt eq substr("reference",0,length($opt)) ) {
  1001. shift(@_) if @_;
  1002. push( @old, $self );
  1003. } else {
  1004. croak "${PACK}->SetOptions: Invalid option ($opt) ",
  1005. "not one of ( @_opt_subs )";
  1006. }
  1007. }
  1008. return wantarray ? @old : $old[-1];
  1009. }
  1010. sub _parseTiedEnt
  1011. {
  1012. my $self= shift(@_);
  1013. $self= tied(%$self) if tied(%$self);
  1014. my $ent= shift(@_);
  1015. my $delim= shift(@_);
  1016. my $dlen= length( $delim );
  1017. my $parent= @_ ? shift(@_) : 0;
  1018. my $off;
  1019. if( $delim x 2 eq substr($ent,0,2*$dlen) && "NONE" eq $self->Handle ) {
  1020. if( 0 <= ( $off= index( $ent, $delim x 2, 2*$dlen ) ) ) {
  1021. ( substr( $ent, 0, $off ), substr( $ent, 2*$dlen+$off ) );
  1022. } elsif( $delim eq substr($ent,-$dlen) ) {
  1023. ( substr($ent,0,-$dlen) );
  1024. } elsif( 2*$dlen <= ( $off= rindex( $ent, $delim ) ) ) {
  1025. ( substr( $ent, 0, $off ), undef, substr( $ent, $dlen+$off ) );
  1026. } elsif( $parent ) {
  1027. ();
  1028. } else {
  1029. ( $ent );
  1030. }
  1031. } elsif( $delim eq substr($ent,0,$dlen) && "NONE" ne $self->Handle ) {
  1032. ( undef, substr($ent,$dlen) );
  1033. } elsif( $self->{MEMBERS} && $self->_MembersHash->{$ent} ) {
  1034. ( substr($ent,0,-$dlen) );
  1035. } elsif( 0 <= ( $off= index( $ent, $delim x 2 ) ) ) {
  1036. ( substr( $ent, 0, $off ), substr( $ent, 2*$dlen+$off ) );
  1037. } elsif( $delim eq substr($ent,-$dlen) ) {
  1038. if( $parent
  1039. && 0 <= ( $off= rindex( $ent, $delim, length($ent)-2*$dlen ) ) ) {
  1040. ( substr($ent,0,$off), undef, undef,
  1041. substr($ent,$dlen+$off,-$dlen) );
  1042. } else {
  1043. ( substr($ent,0,-$dlen) );
  1044. }
  1045. } elsif( 0 <= ( $off= rindex( $ent, $delim ) ) ) {
  1046. ( substr( $ent, 0, $off ), undef, substr( $ent, $dlen+$off ) );
  1047. } else {
  1048. ( undef, undef, $ent );
  1049. }
  1050. }
  1051. sub FETCH
  1052. {
  1053. my $self= shift(@_);
  1054. my $ent= shift(@_);
  1055. my $delim= $self->Delimiter;
  1056. my( $key, $val, $ambig )= $self->_parseTiedEnt( $ent, $delim, 0 );
  1057. my $sub;
  1058. if( defined($key) ) {
  1059. if( defined($self->{MEMBHASH})
  1060. && $self->{MEMBHASH}->{$key.$delim}
  1061. && 0 <= index($key,$delim) ) {
  1062. return wantarray ? () : undef
  1063. unless $sub= $self->new( $key,
  1064. {"Delimiter"=>$self->OS_Delimiter} );
  1065. $sub->Delimiter($delim);
  1066. } else {
  1067. return wantarray ? () : undef
  1068. unless $sub= $self->new( $key );
  1069. }
  1070. } else {
  1071. $sub= $self;
  1072. }
  1073. if( defined($val) ) {
  1074. return $self->ArrayValues ? [ $sub->GetValue( $val ) ]
  1075. : $sub->GetValue( $val );
  1076. } elsif( ! defined($ambig) ) {
  1077. return $sub->TiedRef;
  1078. } elsif( defined($key) ) {
  1079. return $sub->FETCH( $ambig );
  1080. } elsif( "" eq $ambig ) {
  1081. return $self->ArrayValues ? [ $sub->GetValue( $ambig ) ]
  1082. : $sub->GetValue( $ambig );
  1083. } else {
  1084. my $data= [ $sub->GetValue( $ambig ) ];
  1085. return $sub->ArrayValues ? $data : $$data[0]
  1086. if 0 != @$data;
  1087. $data= $sub->new( $ambig );
  1088. return defined($data) ? $data->TiedRef : wantarray ? () : undef;
  1089. }
  1090. }
  1091. sub _FetchOld
  1092. {
  1093. my( $self, $key )= @_;
  1094. my $old= $self->FETCH($key);
  1095. if( $old ) {
  1096. my $copy= {};
  1097. %$copy= %$old;
  1098. return $copy;
  1099. }
  1100. # return $^E;
  1101. return _Err;
  1102. }
  1103. sub DELETE
  1104. {
  1105. my $self= shift(@_);
  1106. my $ent= shift(@_);
  1107. my $delim= $self->Delimiter;
  1108. my( $key, $val, $ambig, $subkey )= $self->_parseTiedEnt( $ent, $delim, 1 );
  1109. my $sub;
  1110. my $fast= defined(wantarray) ? $self->FastDelete : 2;
  1111. my $old= 1; # Value returned if FastDelete is set.
  1112. if( defined($key)
  1113. && ( defined($val) || defined($ambig) || defined($subkey) ) ) {
  1114. return wantarray ? () : undef
  1115. unless $sub= $self->new( $key );
  1116. } else {
  1117. $sub= $self;
  1118. }
  1119. if( defined($val) ) {
  1120. $old= $sub->GetValue($val) || _Err unless 2 <= $fast;
  1121. $sub->RegDeleteValue( $val );
  1122. } elsif( defined($subkey) ) {
  1123. $old= $sub->_FetchOld( $subkey.$delim ) unless $fast;
  1124. $sub->RegDeleteKey( $subkey );
  1125. } elsif( defined($ambig) ) {
  1126. if( defined($key) ) {
  1127. $old= $sub->DELETE($ambig);
  1128. } else {
  1129. $old= $sub->GetValue($ambig) || _Err unless 2 <= $fast;
  1130. if( defined( $old ) ) {
  1131. $sub->RegDeleteValue( $ambig );
  1132. } else {
  1133. $old= $sub->_FetchOld( $ambig.$delim ) unless $fast;
  1134. $sub->RegDeleteKey( $ambig );
  1135. }
  1136. }
  1137. } elsif( defined($key) ) {
  1138. $old= $sub->_FetchOld( $key.$delim ) unless $fast;
  1139. $sub->RegDeleteKey( $key );
  1140. } else {
  1141. croak "${PACK}->DELETE: Key ($ent) can never be deleted";
  1142. }
  1143. $old;
  1144. }
  1145. sub SetValue
  1146. {
  1147. my $self= shift(@_);
  1148. $self= tied(%$self) if tied(%$self);
  1149. my $name= shift(@_);
  1150. my $data= shift(@_);
  1151. my( $type )= @_;
  1152. my $size;
  1153. if( ! defined($type) ) {
  1154. if( "ARRAY" eq ref($data) ) {
  1155. croak "${PACK}->SetValue: Value is array reference but ",
  1156. "no data type given"
  1157. unless 2 == @$data;
  1158. ( $data, $type )= @$data;
  1159. } else {
  1160. $type= REG_SZ;
  1161. }
  1162. }
  1163. $type= Win32API::Registry::constant($type,0) if $type =~ /^REG_/;
  1164. if( REG_MULTI_SZ == $type && "ARRAY" eq ref($data) ) {
  1165. $data= join( "\0", @$data ) . "\0\0";
  1166. ## $data= pack( "a*" x (1+@$data), map( $_."\0", @$data, "" ) );
  1167. } elsif( ( REG_SZ == $type || REG_EXPAND_SZ == $type )
  1168. && $self->FixSzNulls ) {
  1169. $data .= "\0" unless "\0" eq substr($data,0,-1);
  1170. } elsif( REG_DWORD == $type && $data =~ /^0x[0-9a-fA-F]{3,}$/ ) {
  1171. $data= pack( "L", hex($data) );
  1172. # We could to $data=pack("L",$data) for REG_DWORD but I see
  1173. # no nice way to always destinguish when to do this or not.
  1174. }
  1175. $self->RegSetValueEx( $name, 0, $type, $data, length($data) );
  1176. }
  1177. sub StoreKey
  1178. {
  1179. my $this= shift(@_);
  1180. $this= tied(%$this) if ref($this) && tied(%$this);
  1181. my $subKey= shift(@_);
  1182. my $data= shift(@_);
  1183. my $ent;
  1184. my $self;
  1185. if( ! ref($data) || "$data" !~ /(^|=)HASH/ ) {
  1186. croak "${PACK}->StoreKey: For ", $this->Path.$subKey, ",\n",
  1187. " subkey data must be a HASH reference";
  1188. }
  1189. if( defined( $$data{""} ) && "HASH" eq ref($$data{""}) ) {
  1190. $self= $this->CreateKey( $subKey, delete $$data{""} );
  1191. } else {
  1192. $self= $this->CreateKey( $subKey );
  1193. }
  1194. return wantarray ? () : undef if ! defined($self);
  1195. foreach $ent ( keys(%$data) ) {
  1196. return wantarray ? () : undef
  1197. unless $self->STORE( $ent, $$data{$ent} );
  1198. }
  1199. $self;
  1200. }
  1201. # = { "" => {OPT=>VAL}, "val"=>[], "key"=>{} } creates a new key
  1202. # = "string" creates a new REG_SZ value
  1203. # = [ data, type ] creates a new value
  1204. sub STORE
  1205. {
  1206. my $self= shift(@_);
  1207. my $ent= shift(@_);
  1208. my $data= shift(@_);
  1209. my $delim= $self->Delimiter;
  1210. my( $key, $val, $ambig, $subkey )= $self->_parseTiedEnt( $ent, $delim, 1 );
  1211. my $sub;
  1212. if( defined($key)
  1213. && ( defined($val) || defined($ambig) || defined($subkey) ) ) {
  1214. return wantarray ? () : undef
  1215. unless $sub= $self->new( $key );
  1216. } else {
  1217. $sub= $self;
  1218. }
  1219. if( defined($val) ) {
  1220. croak "${PACK}->STORE: For ", $sub->Path.$delim.$val, ",\n",
  1221. " value data cannot be a HASH reference"
  1222. if ref($data) && "$data" =~ /(^|=)HASH/;
  1223. $sub->SetValue( $val, $data );
  1224. } elsif( defined($subkey) ) {
  1225. croak "${PACK}->STORE: For ", $sub->Path.$subkey.$delim, ",\n",
  1226. " subkey data must be a HASH reference"
  1227. unless ref($data) && "$data" =~ /(^|=)HASH/;
  1228. $sub->StoreKey( $subkey, $data );
  1229. } elsif( defined($ambig) ) {
  1230. if( ref($data) && "$data" =~ /(^|=)HASH/ ) {
  1231. $sub->StoreKey( $ambig, $data );
  1232. } else {
  1233. $sub->SetValue( $ambig, $data );
  1234. }
  1235. } elsif( defined($key) ) {
  1236. croak "${PACK}->STORE: For ", $sub->Path.$key.$delim, ",\n",
  1237. " subkey data must be a HASH reference"
  1238. unless ref($data) && "$data" =~ /(^|=)HASH/;
  1239. $sub->StoreKey( $key, $data );
  1240. } else {
  1241. croak "${PACK}->STORE: Key ($ent) can never be created nor set";
  1242. }
  1243. }
  1244. sub EXISTS
  1245. {
  1246. my $self= shift(@_);
  1247. my $ent= shift(@_);
  1248. defined( $self->FETCH($ent) );
  1249. }
  1250. sub FIRSTKEY
  1251. {
  1252. my $self= shift(@_);
  1253. my $members= $self->_MemberNames;
  1254. $self->{PREVIDX}= 0;
  1255. @{$members} ? $members->[0] : undef;
  1256. }
  1257. sub NEXTKEY
  1258. {
  1259. my $self= shift(@_);
  1260. my $prev= shift(@_);
  1261. my $idx= $self->{PREVIDX};
  1262. my $members= $self->_MemberNames;
  1263. if( ! defined($idx) || $prev ne $members->[$idx] ) {
  1264. $idx= 0;
  1265. while( $idx < @$members && $prev ne $members->[$idx] ) {
  1266. $idx++;
  1267. }
  1268. }
  1269. $self->{PREVIDX}= ++$idx;
  1270. $members->[$idx];
  1271. }
  1272. sub DESTROY
  1273. {
  1274. my $self= shift(@_);
  1275. return if tied(%$self);
  1276. my $unload= $self->{UNLOADME};
  1277. my $debug= $ENV{DEBUG_TIE_REGISTRY};
  1278. if( defined($debug) ) {
  1279. if( 1 < $debug ) {
  1280. my $hand= $self->Handle;
  1281. my $dep= $self->{DEPENDON};
  1282. carp "${PACK} destroying ", $self->Path, " (",
  1283. "NONE" eq $hand ? $hand : sprintf("0x%lX",$hand), ")",
  1284. defined($dep) ? (" [depends on ",$dep->Path,"]") : ();
  1285. } else {
  1286. warn "${PACK} destroying ", $self->Path, ".\n";
  1287. }
  1288. }
  1289. $self->RegCloseKey
  1290. unless "NONE" eq $self->Handle;
  1291. if( defined($unload) ) {
  1292. if( defined($debug) && 1 < $debug ) {
  1293. my( $obj, $subKey, $file )= @$unload;
  1294. warn "Unloading ", $self->Path,
  1295. " (from ", $obj->Path, ", $subKey)...\n";
  1296. }
  1297. $self->UnLoad
  1298. || warn "Couldn't unload ", $self->Path, ": ", _ErrMsg, "\n";
  1299. ## carp "Never unloaded ${PACK}::Load($$unload[2])";
  1300. }
  1301. #delete $self->{DEPENDON};
  1302. }
  1303. use vars qw( @CreateKey_Opts %CreateKey_Opts );
  1304. @CreateKey_Opts= qw( Access Class Options Delimiter
  1305. Disposition Security Volatile Backup );
  1306. @CreateKey_Opts{@CreateKey_Opts}= (1) x @CreateKey_Opts;
  1307. sub CreateKey
  1308. {
  1309. my $self= shift(@_);
  1310. my $tied= tied(%$self);
  1311. $self= tied(%$self) if $tied;
  1312. my( $subKey, $opts )= @_;
  1313. my( $sam )= $self->Access;
  1314. my( $delim )= $self->Delimiter;
  1315. my( $class )= "";
  1316. my( $flags )= 0;
  1317. my( $secure )= [];
  1318. my( $garb )= 0;
  1319. my( $result )= \$garb;
  1320. my( $handle )= 0;
  1321. if( @_ < 1 || 2 < @_
  1322. || 2 == @_ && "HASH" ne ref($opts) ) {
  1323. croak "Usage: \$new= \$old->CreateKey( \$subKey, {OPT=>VAL,...} );\n",
  1324. " options: @CreateKey_Opts\nCalled";
  1325. }
  1326. if( defined($opts) ) {
  1327. $sam= $opts->{"Access"} if defined($opts->{"Access"});
  1328. $class= $opts->{Class} if defined($opts->{Class});
  1329. $flags= $opts->{Options} if defined($opts->{Options});
  1330. $delim= $opts->{"Delimiter"} if defined($opts->{"Delimiter"});
  1331. $secure= $opts->{Security} if defined($opts->{Security});
  1332. if( defined($opts->{Disposition}) ) {
  1333. "SCALAR" eq ref($opts->{Disposition})
  1334. or croak "${PACK}->CreateKey option `Disposition'",
  1335. " must provide a scalar reference";
  1336. $result= $opts->{Disposition};
  1337. }
  1338. $result= ${$opts->{Disposition}} if defined($opts->{Disposition});
  1339. if( 0 == $flags ) {
  1340. $flags |= REG_OPTION_VOLATILE
  1341. if defined($opts->{Volatile}) && $opts->{Volatile};
  1342. $flags |= REG_OPTION_BACKUP_RESTORE
  1343. if defined($opts->{Backup}) && $opts->{Backup};
  1344. }
  1345. }
  1346. my $subPath= ref($subKey) ? $subKey : $self->_split($subKey,$delim);
  1347. $subKey= join( $self->OS_Delimiter, @$subPath );
  1348. $self->RegCreateKeyEx( $subKey, 0, $class, $flags, $sam,
  1349. $secure, $handle, $$result )
  1350. or return wantarray ? () : undef;
  1351. my $new= $self->_new( $handle, [ @{$self->_Path}, @{$subPath} ] );
  1352. $new->{ACCESS}= $sam;
  1353. $new->{DELIM}= $delim;
  1354. $new= $new->TiedRef if $tied;
  1355. return $new;
  1356. }
  1357. use vars qw( $Load_Cnt @Load_Opts %Load_Opts );
  1358. $Load_Cnt= 0;
  1359. @Load_Opts= qw(NewSubKey);
  1360. @Load_Opts{@Load_Opts}= (1) x @Load_Opts;
  1361. sub Load
  1362. {
  1363. my $this= shift(@_);
  1364. my $tied= ref($this) && tied(%$this);
  1365. $this= tied(%$this) if $tied;
  1366. my( $file, $subKey, $opts )= @_;
  1367. if( 2 == @_ && "HASH" eq ref($subKey) ) {
  1368. $opts= $subKey;
  1369. undef $subKey;
  1370. }
  1371. @_ < 1 || 3 < @_ || defined($opts) && "HASH" ne ref($opts)
  1372. and croak "Usage: \$key= ",
  1373. "${PACK}->Load( \$fileName, [\$newSubKey,] {OPT=>VAL...} );\n",
  1374. " options: @Load_Opts @new_Opts\nCalled";
  1375. if( defined($opts) && exists($opts->{NewSubKey}) ) {
  1376. $subKey= delete $opts->{NewSubKey};
  1377. }
  1378. if( ! defined( $subKey ) ) {
  1379. if( "" ne $this->Machine ) {
  1380. ( $this )= $this->_connect( [$this->Machine,"LMachine"] );
  1381. } else {
  1382. ( $this )= $this->_rootKey( "LMachine" ); # Could also be "Users"
  1383. }
  1384. $subKey= "PerlTie:$$." . ++$Load_Cnt;
  1385. }
  1386. $this->RegLoadKey( $subKey, $file )
  1387. or return wantarray ? () : undef;
  1388. my $self= $this->new( $subKey, defined($opts) ? $opts : () );
  1389. if( ! defined( $self ) ) {
  1390. { my $err= Win32::GetLastError();
  1391. #{ local( $^E );
  1392. $this->RegUnLoadKey( $subKey )
  1393. or carp "Can't unload $subKey from ", $this->Path, ": $^E\n";
  1394. Win32::SetLastError($err);
  1395. }
  1396. return wantarray ? () : undef;
  1397. }
  1398. $self->{UNLOADME}= [ $this, $subKey, $file ];
  1399. $self= $self->TiedRef if $tied;
  1400. $self;
  1401. }
  1402. sub UnLoad
  1403. {
  1404. my $self= shift(@_);
  1405. $self= tied(%$self) if tied(%$self);
  1406. @_ and croak "Usage: \$key->UnLoad;";
  1407. my $unload= $self->{UNLOADME};
  1408. "ARRAY" eq ref($unload)
  1409. or croak "${PACK}->UnLoad called on a key which was not Load()ed";
  1410. my( $obj, $subKey, $file )= @$unload;
  1411. $self->RegCloseKey;
  1412. Win32API::Registry::RegUnLoadKey( $obj->Handle, $subKey );
  1413. }
  1414. sub AllowSave
  1415. {
  1416. my $self= shift(@_);
  1417. $self= tied(%$self) if tied(%$self);
  1418. $self->AllowPriv( "SeBackupPrivilege", @_ );
  1419. }
  1420. sub AllowLoad
  1421. {
  1422. my $self= shift(@_);
  1423. $self= tied(%$self) if tied(%$self);
  1424. $self->AllowPriv( "SeRestorePrivilege", @_ );
  1425. }
  1426. # RegNotifyChangeKeyValue( hKey, bWatchSubtree, iNotifyFilter, hEvent, bAsync )
  1427. sub RegCloseKey { my $self= shift(@_);
  1428. Win32API::Registry::RegCloseKey $self->Handle, @_; }
  1429. sub RegConnectRegistry { my $self= shift(@_);
  1430. Win32API::Registry::RegConnectRegistry @_; }
  1431. sub RegCreateKey { my $self= shift(@_);
  1432. Win32API::Registry::RegCreateKey $self->Handle, @_; }
  1433. sub RegCreateKeyEx { my $self= shift(@_);
  1434. Win32API::Registry::RegCreateKeyEx $self->Handle, @_; }
  1435. sub RegDeleteKey { my $self= shift(@_);
  1436. Win32API::Registry::RegDeleteKey $self->Handle, @_; }
  1437. sub RegDeleteValue { my $self= shift(@_);
  1438. Win32API::Registry::RegDeleteValue $self->Handle, @_; }
  1439. sub RegEnumKey { my $self= shift(@_);
  1440. Win32API::Registry::RegEnumKey $self->Handle, @_; }
  1441. sub RegEnumKeyEx { my $self= shift(@_);
  1442. Win32API::Registry::RegEnumKeyEx $self->Handle, @_; }
  1443. sub RegEnumValue { my $self= shift(@_);
  1444. Win32API::Registry::RegEnumValue $self->Handle, @_; }
  1445. sub RegFlushKey { my $self= shift(@_);
  1446. Win32API::Registry::RegFlushKey $self->Handle, @_; }
  1447. sub RegGetKeySecurity { my $self= shift(@_);
  1448. Win32API::Registry::RegGetKeySecurity $self->Handle, @_; }
  1449. sub RegLoadKey { my $self= shift(@_);
  1450. Win32API::Registry::RegLoadKey $self->Handle, @_; }
  1451. sub RegNotifyChangeKeyValue { my $self= shift(@_);
  1452. Win32API::Registry::RegNotifyChangeKeyValue $self->Handle, @_; }
  1453. sub RegOpenKey { my $self= shift(@_);
  1454. Win32API::Registry::RegOpenKey $self->Handle, @_; }
  1455. sub RegOpenKeyEx { my $self= shift(@_);
  1456. Win32API::Registry::RegOpenKeyEx $self->Handle, @_; }
  1457. sub RegQueryInfoKey { my $self= shift(@_);
  1458. Win32API::Registry::RegQueryInfoKey $self->Handle, @_; }
  1459. sub RegQueryMultipleValues { my $self= shift(@_);
  1460. Win32API::Registry::RegQueryMultipleValues $self->Handle, @_; }
  1461. sub RegQueryValue { my $self= shift(@_);
  1462. Win32API::Registry::RegQueryValue $self->Handle, @_; }
  1463. sub RegQueryValueEx { my $self= shift(@_);
  1464. Win32API::Registry::RegQueryValueEx $self->Handle, @_; }
  1465. sub RegReplaceKey { my $self= shift(@_);
  1466. Win32API::Registry::RegReplaceKey $self->Handle, @_; }
  1467. sub RegRestoreKey { my $self= shift(@_);
  1468. Win32API::Registry::RegRestoreKey $self->Handle, @_; }
  1469. sub RegSaveKey { my $self= shift(@_);
  1470. Win32API::Registry::RegSaveKey $self->Handle, @_; }
  1471. sub RegSetKeySecurity { my $self= shift(@_);
  1472. Win32API::Registry::RegSetKeySecurity $self->Handle, @_; }
  1473. sub RegSetValue { my $self= shift(@_);
  1474. Win32API::Registry::RegSetValue $self->Handle, @_; }
  1475. sub RegSetValueEx { my $self= shift(@_);
  1476. Win32API::Registry::RegSetValueEx $self->Handle, @_; }
  1477. sub RegUnLoadKey { my $self= shift(@_);
  1478. Win32API::Registry::RegUnLoadKey $self->Handle, @_; }
  1479. sub AllowPriv { my $self= shift(@_);
  1480. Win32API::Registry::AllowPriv @_; }
  1481. # Autoload methods go after =cut, and are processed by the autosplit program.
  1482. 1;
  1483. __END__
  1484. =head1 NAME
  1485. Win32::TieRegistry - Powerful and easy ways to manipulate a registry
  1486. [on Win32 for now].
  1487. =head1 SYNOPSIS
  1488. use Win32::TieRegistry 0.20 ( UseOptionName=>UseOptionValue[,...] );
  1489. $Registry->SomeMethodCall(arg1,...);
  1490. $subKey= $Registry->{"Key\\SubKey\\"};
  1491. $valueData= $Registry->{"Key\\SubKey\\\\ValueName"};
  1492. $Registry->{"Key\\SubKey\\"}= { "NewSubKey" => {...} };
  1493. $Registry->{"Key\\SubKey\\\\ValueName"}= "NewValueData";
  1494. $Registry->{"\\ValueName"}= [ pack("fmt",$data), REG_DATATYPE ];
  1495. =head1 EXAMPLES
  1496. use Win32::TieRegistry( Delimiter=>"#", ArrayValues=>0 );
  1497. $pound= $Registry->Delimiter("/");
  1498. $diskKey= $Registry->{"LMachine/System/Disk/"}
  1499. or die "Can't read LMachine/System/Disk key: $^E\n";
  1500. $data= $key->{"/Information"}
  1501. or die "Can't read LMachine/System/Disk//Information value: $^E\n";
  1502. $remoteKey= $Registry->{"//ServerA/LMachine/System/"}
  1503. or die "Can't read //ServerA/LMachine/System/ key: $^E\n";
  1504. $remoteData= $remoteKey->{"Disk//Information"}
  1505. or die "Can't read ServerA's System/Disk//Information value: $^E\n";
  1506. foreach $entry ( keys(%$diskKey) ) {
  1507. ...
  1508. }
  1509. foreach $subKey ( $diskKey->SubKeyNames ) {
  1510. ...
  1511. }
  1512. $diskKey->AllowSave( 1 );
  1513. $diskKey->RegSaveKey( "C:/TEMP/DiskReg", [] );
  1514. =head1 DESCRIPTION
  1515. The I<Win32::TieRegistry> module lets you manipulate the Registry
  1516. via objects [as in "object oriented"] or via tied hashes. But
  1517. you will probably mostly use a combination reference, that is, a
  1518. reference to a tied hash that has also been made an object so that
  1519. you can mix both access methods [as shown above].
  1520. If you did not get this module as part of libwin32, you might
  1521. want to get a recent version of libwin32 from CPAN which should
  1522. include this module and the C<Win32API::Registry> module that it
  1523. uses.
  1524. Skip to the L<SUMMARY> section if you just want to dive in and start
  1525. using the Registry from Perl.
  1526. Accessing and manipulating the registry is extremely simple using
  1527. I<Win32::TieRegistry>. A single, simple expression can return
  1528. you almost any bit of information stored in the Registry.
  1529. I<Win32::TieRegistry> also gives you full access to the "raw"
  1530. underlying API calls so that you can do anything with the Registry
  1531. in Perl that you could do in C. But the "simple" interface has
  1532. been carefully designed to handle almost all operations itself
  1533. without imposing arbitrary limits while providing sensible
  1534. defaults so you can list only the parameters you care about.
  1535. But first, an overview of the Registry itself.
  1536. =head2 The Registry
  1537. The Registry is a forest: a collection of several tree structures.
  1538. The root of each tree is a key. These root keys are identified by
  1539. predefined constants whose names start with "HKEY_". Although all
  1540. keys have a few attributes associated with each [a class, a time
  1541. stamp, and security information], the most important aspect of keys
  1542. is that each can contain subkeys and can contain values.
  1543. Each subkey has a name: a string which cannot be blank and cannot
  1544. contain the delimiter character [backslash: C<'\\'>] nor nul
  1545. [C<'\0'>]. Each subkey is also a key and so can contain subkeys
  1546. and values [and has a class, time stamp, and security information].
  1547. Each value has a name: a string which E<can> be blank and E<can>
  1548. contain the delimiter character [backslash: C<'\\'>] and any
  1549. character except for null, C<'\0'>. Each value also has data
  1550. associated with it. Each value's data is a contiguous chunk of
  1551. bytes, which is exactly what a Perl string value is so Perl
  1552. strings will usually be used to represent value data.
  1553. Each value also has a data type which says how to interpret the
  1554. value data. The primary data types are:
  1555. =over
  1556. =item REG_SZ
  1557. A null-terminated string.
  1558. =item REG_EXPAND_SZ
  1559. A null-terminated string which contains substrings consisting of a
  1560. percent sign [C<'%'>], an environment variable name, then a percent
  1561. sign, that should be replaced with the value associate with that
  1562. environment variable. The system does I<not> automatically do this
  1563. substitution.
  1564. =item REG_BINARY
  1565. Some arbitrary binary value. You can think of these as being
  1566. "packed" into a string.
  1567. If your system has the L<SetDualVar> module installed,
  1568. the C<DualBinVals()> option wasn't turned off, and you
  1569. fetch a C<REG_BINARY> value of 4 bytes or fewer, then
  1570. you can use the returned value in a numeric context to
  1571. get at the "unpacked" numeric value. See C<GetValue()>
  1572. for more information.
  1573. =item REG_MULTI_SZ
  1574. Several null-terminated strings concatenated together with an
  1575. extra trailing C<'\0'> at the end of the list. Note that the list
  1576. can include empty strings so use the value's length to determine
  1577. the end of the list, not the first occurrence of C<'\0\0'>.
  1578. It is best to set the C<SplitMultis()> option so I<Win32::TieRegistry>
  1579. will split these values into an array of strings for you.
  1580. =item REG_DWORD
  1581. A long [4-byte] integer value. These values are expected either
  1582. packed into a 4-character string or as a hex string of E<more than>
  1583. 4 characters [but I<not> as a numeric value, unfortunately, as there is
  1584. no sure way to tell a numeric value from a packed 4-byte string that
  1585. just happens to be a string containing a valid numeric value].
  1586. How such values are returned depends on the C<DualBinVals()> and
  1587. C<DWordsToHex()> options. See C<GetValue()> for details.
  1588. =back
  1589. In the underlying Registry calls, most places which take a
  1590. subkey name also allow you to pass in a subkey "path" -- a
  1591. string of several subkey names separated by the delimiter
  1592. character, backslash [C<'\\'>]. For example, doing
  1593. C<RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SYSTEM\\DISK",...)>
  1594. is much like opening the C<"SYSTEM"> subkey of C<HKEY_LOCAL_MACHINE>,
  1595. then opening its "DISK" subkey, then closing the C<"SYSTEM"> subkey.
  1596. All of the I<Win32::TieRegistry> features allow you to use your
  1597. own delimiter in place of the system's delimiter, [C<'\\'>]. In
  1598. most of our examples we will use a forward slash [C<'/'>] as our
  1599. delimiter as it is easier to read and less error prone to use when
  1600. writing Perl code since you have to type two backslashes for each
  1601. backslash you want in a string. Note that this is true even when
  1602. using single quotes -- C<'\\HostName\LMachine\'> is an invalid
  1603. string and must be written as C<'\\\\HostName\\LMachine\\'>.
  1604. You can also connect to the registry of other computers on your
  1605. network. This will be discussed more later.
  1606. Although the Registry does not have a single root key, the
  1607. I<Win32::TieRegistry> module creates a virtual root key for you
  1608. which has all of the I<HKEY_*> keys as subkeys.
  1609. =head2 Tied Hashes Documentation
  1610. Before you can use a tied hash, you must create one. One way to
  1611. do that is via:
  1612. use Win32::TieRegistry ( TiedHash => '%RegHash' );
  1613. which exports a C<%RegHash> variable into your package and ties it
  1614. to the virtual root key of the Registry. An alternate method is:
  1615. my %RegHash;
  1616. use Win32::TieRegistry ( TiedHash => \%RegHash );
  1617. There are also several ways you can tie a hash variable to any
  1618. other key of the Registry, which are discussed later.
  1619. Note that you will most likely use C<$Registry> instead of using
  1620. a tied hash. C<$Registry> is a reference to a hash that has
  1621. been tied to the virtual root of your computer's Registry [as if,
  1622. C<$Registry= \%RegHash>]. So you would use C<$Registry-E<gt>{Key}>
  1623. rather than C<$RegHash{Key}> and use C<keys %{$Registry}> rather
  1624. than C<keys %RegHash>, for example.
  1625. For each hash which has been tied to a Registry key, the Perl
  1626. C<keys> function will return a list containing the name of each
  1627. of the key's subkeys with a delimiter character appended to it and
  1628. containing the name of each of the key's values with a delimiter
  1629. prepended to it. For example:
  1630. keys( %{ $Registry->{"HKEY_CLASSES_ROOT\\batfile\\"} } )
  1631. might yield the following list value:
  1632. ( "DefaultIcon\\", # The subkey named "DefaultIcon"
  1633. "shell\\", # The subkey named "shell"
  1634. "shellex\\", # The subkey named "shellex"
  1635. "\\", # The default value [named ""]
  1636. "\\EditFlags" ) # The value named "EditFlags"
  1637. For the virtual root key, short-hand subkey names are used as
  1638. shown below. You can use the short-hand name, the regular
  1639. I<HKEY_*> name, or any numeric value to access these keys, but
  1640. the short-hand names are all that will be returned by the C<keys>
  1641. function.
  1642. =over
  1643. =item "Classes" for HKEY_CLASSES_ROOT
  1644. Contains mappings between file name extensions and the uses
  1645. for such files along with configuration information for COM
  1646. [MicroSoft's Common Object Model] objects. Usually a link to
  1647. the C<"SOFTWARE\\Classes"> subkey of the C<HKEY_LOCAL_MACHINE>
  1648. key.
  1649. =item "CUser" for HKEY_CURRENT_USER
  1650. Contains information specific to the currently logged-in user.
  1651. Mostly software configuration information. Usually a link to
  1652. a subkey of the C<HKEY_USERS> key.
  1653. =item "LMachine" for HKEY_LOCAL_MACHINE
  1654. Contains all manner of information about the computer.
  1655. =item "Users" for HKEY_USERS
  1656. Contains one subkey, C<".DEFAULT">, which gets copied to a new
  1657. subkey whenever a new user is added. Also contains a subkey for
  1658. each user of the system, though only those for active users
  1659. [usually only one] are loaded at any given time.
  1660. =item "PerfData" for HKEY_PERFORMANCE_DATA
  1661. Used to access data about system performance. Access via this key
  1662. is "special" and all but the most carefully constructed calls will
  1663. fail, usually with C<ERROR_INSUFFICIENT_BUFFER>. For example, you
  1664. can't enumerate key names without also enumerating values which
  1665. require huge buffers but the exact buffer size required cannot be
  1666. determined beforehand because C<RegQueryInfoKey()> E<always> fails
  1667. with C<ERROR_INSUFFICIENT_BUFFER> for C<HKEY_PERFORMANCE_DATA> no
  1668. matter how it is called. So it is currently not very useful to
  1669. tie a hash to this key. You can use it to create an object to use
  1670. for making carefully constructed calls to the underlying Reg*()
  1671. routines.
  1672. =item "CConfig" for HKEY_CURRENT_CONFIG
  1673. Contains minimal information about the computer's current
  1674. configuration that is required very early in the boot process.
  1675. For example, setting for the display adapter such as screen
  1676. resolution and refresh rate are found in here.
  1677. =item "DynData" for HKEY_DYN_DATA
  1678. Dynamic data. We have found no documentation for this key.
  1679. =back
  1680. A tied hash is much like a regular hash variable in Perl -- you give
  1681. it a key string inside braces, [C<{> and C<}>], and it gives you
  1682. back a value [or lets you set a value]. For I<Win32::TieRegistry>
  1683. hashes, there are two types of values that will be returned.
  1684. =over
  1685. =item SubKeys
  1686. If you give it a string which represents a subkey, then it will
  1687. give you back a reference to a hash which has been tied to that
  1688. subkey. It can't return the hash itself, so it returns a
  1689. reference to it. It also blesses that reference so that it is
  1690. also an object so you can use it to call method functions.
  1691. =item Values
  1692. If you give it a string which is a value name, then it will give
  1693. you back a string which is the data for that value. Alternately,
  1694. you can request that it give you both the data value string and
  1695. the data value type [we discuss how to request this later]. In
  1696. this case, it would return a reference to an array where the value
  1697. data string is element C<[0]> and the value data type is element
  1698. C<[1]>.
  1699. =back
  1700. The key string which you use in the tied hash must be interpreted
  1701. to determine whether it is a value name or a key name or a path
  1702. that combines several of these or even other things. There are
  1703. two simple rules that make this interpretation easy and
  1704. unambiguous:
  1705. Put a delimiter after each key name.
  1706. Put a delimiter in front of each value name.
  1707. Exactly how the key string will be intepreted is governed by the
  1708. following cases, in the order listed. These cases are designed
  1709. to "do what you mean". Most of the time you won't have to think
  1710. about them, especially if you follow the two simple rules above.
  1711. After the list of cases we give several examples which should be
  1712. clear enough so feel free to skip to them unless you are worried
  1713. about the details.
  1714. =over
  1715. =item Remote machines
  1716. If the hash is tied to the virtual root of the registry [or the
  1717. virtual root of a remote machine's registry], then we treat hash
  1718. key strings which start with the delimiter character specially.
  1719. If the hash key string starts with two delimiters in a row, then
  1720. those should be immediately followed by the name of a remote
  1721. machine whose registry we wish to connect to. That can be
  1722. followed by a delimiter and more subkey names, etc. If the
  1723. machine name is not following by anything, then a virtual root
  1724. for the remote machine's registry is created, a hash is tied to
  1725. it, and a reference to that hash it is returned.
  1726. =item Hash key string starts with the delimiter
  1727. If the hash is tied to a virtual root key, then the leading
  1728. delimiter is ignored. It should be followed by a valid Registry
  1729. root key name [either a short-hand name like C<"LMachine">, an
  1730. I<HKEY_*> value, or a numeric value]. This alternate notation is
  1731. allowed in order to be more consistant with the C<Open()> method
  1732. function.
  1733. For all other Registry keys, the leading delimiter indicates
  1734. that the rest of the string is a value name. The leading
  1735. delimiter is stripped and the rest of the string [which can
  1736. be empty and can contain more delimiters] is used as a value
  1737. name with no further parsing.
  1738. =item Exact match with direct subkey name followed by delimiter
  1739. If you have already called the Perl C<keys> function on the tied
  1740. hash [or have already called C<MemberNames> on the object] and the
  1741. hash key string exactly matches one of the strings returned, then
  1742. no further parsing is done. In other words, if the key string
  1743. exactly matches the name of a direct subkey with a delimiter
  1744. appended, then a reference to a hash tied to that subkey is
  1745. returned [but only if C<keys> or C<MemberNames> has already
  1746. been called for that tied hash].
  1747. This is only important if you have selected a delimiter other than
  1748. the system default delimiter and one of the subkey names contains
  1749. the delimiter you have chosen. This rule allows you to deal with
  1750. subkeys which contain your chosen delimiter in their name as long
  1751. as you only traverse subkeys one level at a time and always
  1752. enumerate the list of members before doing so.
  1753. The main advantage of this is that Perl code which recursively
  1754. traverses a hash will work on hashes tied to Registry keys even if
  1755. a non-default delimiter has been selected.
  1756. =item Hash key string contains two delimiters in a row
  1757. If the hash key string contains two [or more] delimiters in a row,
  1758. then the string is split between the first pair of delimiters.
  1759. The first part is interpreted as a subkey name or a path of subkey
  1760. names separated by delimiters and with a trailing delimiter. The
  1761. second part is interpreted as a value name with one leading
  1762. delimiter [any extra delimiters are considered part of the value
  1763. name].
  1764. =item Hash key string ends with a delimiter
  1765. If the key string ends with a delimiter, then it is treated
  1766. as a subkey name or path of subkey names separated by delimiters.
  1767. =item Hash key string contains a delimiter
  1768. If the key string contains a delimiter, then it is split after
  1769. the last delimiter. The first part is treated as a subkey name or
  1770. path of subkey names separated by delimiters. The second part
  1771. is ambiguous and is treated as outlined in the next item.
  1772. =item Hash key string contains no delimiters
  1773. If the hash key string contains no delimiters, then it is ambiguous.
  1774. If you are reading from the hash [fetching], then we first use the
  1775. key string as a value name. If there is a value with a matching
  1776. name in the Registry key which the hash is tied to, then the value
  1777. data string [and possibly the value data type] is returned.
  1778. Otherwise, we retry by using the hash key string as a subkey name.
  1779. If there is a subkey with a matching name, then we return a
  1780. reference to a hash tied to that subkey. Otherwise we return
  1781. C<undef>.
  1782. If you are writing to the hash [storing], then we use the key
  1783. string as a subkey name only if the value you are storing is a
  1784. reference to a hash value. Otherwise we use the key string as
  1785. a value name.
  1786. =back
  1787. =head3 Examples
  1788. Here are some examples showing different ways of accessing Registry
  1789. information using references to tied hashes:
  1790. =over
  1791. =item Canonical value fetch
  1792. $tip18= $Registry->{"HKEY_LOCAL_MACHINE\\Software\\Microsoft\\"
  1793. . 'Windows\\CurrentVersion\\Explorer\\Tips\\\\18'};
  1794. Should return the text of important tip number 18. Note that two
  1795. backslashes, C<"\\">, are required to get a single backslash into
  1796. a Perl double-quoted or single-qouted string. Note that C<"\\">
  1797. is appended to each key name [C<"HKEY_LOCAL_MACHINE"> through
  1798. C<"Tips">] and C<"\\"> is prepended to the value name, C<"18">.
  1799. =item Changing your delimiter
  1800. $Registry->Delimiter("/");
  1801. $tip18= $Registry->{"HKEY_LOCAL_MACHINE/Software/Microsoft/"
  1802. . 'Windows/CurrentVersion/Explorer/Tips//18'};
  1803. This usually makes things easier to read when working in Perl.
  1804. All remaining examples will assume the delimiter has been changed
  1805. as above.
  1806. =item Using intermediate keys
  1807. $ms= $Registry->{"LMachine/Software/Microsoft/"};
  1808. $tips= $ms->{"Windows/CurrentVersion/Explorer/Tips/"};
  1809. $tip18= $winlogon->{"/18"};
  1810. Same as above but opens more keys into the Registry which lets you
  1811. efficiently re-access those intermediate keys. This is slightly
  1812. less efficient if you never reuse those intermediate keys.
  1813. =item Chaining in a single statement
  1814. $tip18= $Registry->{"LMachine/Software/Microsoft/"}->
  1815. {"Windows/CurrentVersion/Explorer/Tips/"}->{"/18"};
  1816. Like above, this creates intermediate key objects then uses
  1817. them to access other data. Once this statement finishes, the
  1818. intermediate key objects are destroyed. Several handles into
  1819. the Registry are opened and closed by this statement so it is
  1820. less efficient but there are times when this will be useful.
  1821. =item Even less efficient example of chaining
  1822. $tip18= $Registry->{"LMachine/Software/Microsoft"}->
  1823. {"Windows/CurrentVersion/Explorer/Tips"}->{"/18"};
  1824. Because we left off the trailing delimiters, I<Win32::TieRegistry>
  1825. doesn't know whether final names, C<"Microsoft"> and C<"Tips">,
  1826. are subkey names or value names. So this statement ends up
  1827. executing the same code as the next one.
  1828. =item What the above really does
  1829. $tip18= $Registry->{"LMachine/Software/"}->{"Microsoft"}->
  1830. {"Windows/CurrentVersion/Explorer/"}->{"Tips"}->{"/18"};
  1831. With more chains to go through, more temporary objects are created
  1832. and later destroyed than in our first chaining example. Also,
  1833. when C<"Microsoft"> is looked up, I<Win32::TieRegistry> first
  1834. tries to open it as a value and fails then tries it as a subkey.
  1835. The same is true for when it looks up C<"Tips">.
  1836. =item Getting all of the tips
  1837. $tips= $Registry->{"LMachine/Software/Microsoft/"}->
  1838. {"Windows/CurrentVersion/Explorer/Tips/"}
  1839. or die "Can't find the Windows tips: $^E\n";
  1840. foreach( keys %$tips ) {
  1841. print "$_: ", $tips->{$_}, "\n";
  1842. }
  1843. First notice that we actually check for failure for the first time.
  1844. Note that your version of Perl may not set C<$^E> properly [see
  1845. the L<BUGS> section]. We are assuming that the C<"Tips"> key
  1846. contains no subkeys. Otherwise the C<print> statement would show
  1847. something like C<"Win32::TieRegistry=HASH(0xc03ebc)"> for each subkey.
  1848. The output from the above code will start something like:
  1849. /0: If you don't know how to do something,[...]
  1850. =back
  1851. =head3 Deleting items
  1852. You can use the Perl C<delete> function to delete a value from a
  1853. Registry key or to delete a subkey as long that subkey contains
  1854. no subkeys of its own. See L<More Examples>, below, for more
  1855. information.
  1856. =head3 Storing items
  1857. You can use the Perl assignment operator [C<=>] to create new
  1858. keys, create new values, or replace values. The values you store
  1859. should be in the same format as the values you would fetch from a
  1860. tied hash. For example, you can use a single assignment statement
  1861. to copy an entire Registry tree. The following statement:
  1862. $Registry->{"LMachine/Software/Classes/Tie_Registry/"}=
  1863. $Registry->{"LMachine/Software/Classes/batfile/"};
  1864. creates a C<"Tie_Registry"> subkey under the C<"Software\\Classes">
  1865. subkey of the C<HKEY_LOCAL_MACHINE> key. Then it populates it
  1866. with copies of all of the subkeys and values in the C<"batfile">
  1867. subkey and all of its subkeys. Note that you need to have
  1868. called C<$Registry-E<gt>ArrayValues(1)> for the proper value data
  1869. type information to be copied. Note also that this release of
  1870. I<Win32::TieRegistry> does not copy key attributes such as class
  1871. name and security information [this is planned for a future release].
  1872. The following statement creates a whole subtree in the Registry:
  1873. $Registry->{"LMachine/Software/FooCorp/"}= {
  1874. "FooWriter/" => {
  1875. "/Version" => "4.032",
  1876. "Startup/" => {
  1877. "/Title" => "Foo Writer Deluxe ][",
  1878. "/WindowSize" => [ pack("LL",$wid,$ht), REG_BINARY ],
  1879. "/TaskBarIcon" => [ "0x0001", REG_DWORD ],
  1880. },
  1881. "Compatibility/" => {
  1882. "/AutoConvert" => "Always",
  1883. "/Default Palette" => "Windows Colors",
  1884. },
  1885. },
  1886. "/License", => "0123-9C8EF1-09-FC",
  1887. };
  1888. Note that all but the last Registry key used on the left-hand
  1889. side of the assignment [that is, "LMachine/Software/" but not
  1890. "FooCorp/"] must already exist for this statement to succeed.
  1891. By using the leading a trailing delimiters on each subkey name and
  1892. value name, I<Win32::TieRegistry> will tell you if you try to assign
  1893. subkey information to a value or visa-versa.
  1894. =head3 More examples
  1895. =over
  1896. =item Adding a new tip
  1897. $tips= $Registry->{"LMachine/Software/Microsoft/"}->
  1898. {"Windows/CurrentVersion/Explorer/Tips/"}
  1899. or die "Can't find the Windows tips: $^E\n";
  1900. $tips{'/186'}= "Be very careful when making changes to the Registry!";
  1901. =item Deleting our new tip
  1902. $tips= $Registry->{"LMachine/Software/Microsoft/"}->
  1903. {"Windows/CurrentVersion/Explorer/Tips/"}
  1904. or die "Can't find the Windows tips: $^E\n";
  1905. $tip186= delete $tips{'/186'};
  1906. Note that Perl's C<delete> function returns the value that was deleted.
  1907. =item Adding a new tip differently
  1908. $Registry->{"LMachine/Software/Microsoft/" .
  1909. "Windows/CurrentVersion/Explorer/Tips//186"}=
  1910. "Be very careful when making changes to the Registry!";
  1911. =item Deleting differently
  1912. $tip186= delete $Registry->{"LMachine/Software/Microsoft/Windows/" .
  1913. "CurrentVersion/Explorer/Tips//186"};
  1914. Note that this only deletes the tail of what we looked up, the
  1915. C<"186"> value, not any of the keys listed.
  1916. =item Deleting a key
  1917. WARNING: The following code will delete all information about the
  1918. current user's tip preferences. Actually executing this command
  1919. would probably cause the user to see the Welcome screen the next
  1920. time they log in and may cause more serious problems. This
  1921. statement is shown as an example only and should not be used when
  1922. experimenting.
  1923. $tips= delete $Registry->{"CUser/Software/Microsoft/Windows/" .
  1924. "CurrentVersion/Explorer/Tips/"};
  1925. This deletes the C<"Tips"> key and the values it contains. The
  1926. C<delete> function will return a reference to a hash [not a tied
  1927. hash] containing the value names and value data that were deleted.
  1928. The information to be returned is copied from the Registry into a
  1929. regular Perl hash before the key is deleted. If the key has many
  1930. subkeys, this copying could take a significant amount of memory
  1931. and/or processor time. So you can disable this process by calling
  1932. the C<FastDelete> member function:
  1933. $prevSetting= $regKey->FastDelete(1);
  1934. which will cause all subsequent delete operations via C<$regKey>
  1935. to simply return a true value if they succeed. This optimization
  1936. is automatically done if you use C<delete> in a void context.
  1937. =item Technical notes on deleting
  1938. If you use C<delete> to delete a Registry key or value and use
  1939. the return value, then C<Win32::TieRegistry> usually looks up the
  1940. current contents of that key or value so they can be returned if
  1941. the deletion is successful. If the deletion succeeds but the
  1942. attempt to lookup the old contents failed, then the return value
  1943. of C<delete> will be C<$^E> from the failed part of the operation.
  1944. =item Undeleting a key
  1945. $Registry->{"LMachine/Software/Microsoft/Windows/" .
  1946. "CurrentVersion/Explorer/Tips/"}= $tips;
  1947. This adds back what we just deleted. Note that this version of
  1948. I<Win32::TieRegistry> will use defaults for the key attributes
  1949. [such as class name and security] and will not restore the
  1950. previous attributes.
  1951. =item Not deleting a key
  1952. WARNING: Actually executing the following code could cause
  1953. serious problems. This statement is shown as an example only and
  1954. should not be used when experimenting.
  1955. $res= delete $Registry->{"CUser/Software/Microsoft/Windows/"}
  1956. defined($res) || die "Can't delete URL key: $^E\n";
  1957. Since the "Windows" key should contain subkeys, that C<delete>
  1958. statement should make no changes to the Registry, return C<undef>,
  1959. and set C<$^E> to "Access is denied" [but see the L<BUGS> section
  1960. about C<$^E>].
  1961. =item Not deleting again
  1962. $tips= $Registry->{"CUser/Software/Microsoft/Windows/" .
  1963. "CurrentVersion/Explorer/Tips/"};
  1964. delete $tips;
  1965. The Perl C<delete> function requires that its argument be an
  1966. expression that ends in a hash element lookup [or hash slice],
  1967. which is not the case here. The C<delete> function doesn't
  1968. know which hash $tips came from and so can't delete it.
  1969. =back
  1970. =head2 Objects Documentation
  1971. The following member functions are defined for use on
  1972. I<Win32::TieRegistry> objects:
  1973. =over
  1974. =item new
  1975. The C<new> method creates a new I<Win32::TieRegistry> object.
  1976. C<new> is mostly a synonym for C<Open()> so see C<Open()> below for
  1977. information on what arguments to pass in. Examples:
  1978. $machKey= new Win32::TieRegistry "LMachine"
  1979. or die "Can't access HKEY_LOCAL_MACHINE key: $^E\n";
  1980. $userKey= Win32::TieRegistry->new("CUser")
  1981. or die "Can't access HKEY_CURRENT_USER key: $^E\n";
  1982. Note that calling C<new> via a reference to a tied hash returns
  1983. a simple object, not a reference to a tied hash.
  1984. =item Open
  1985. =item $subKey= $key->Open( $sSubKey, $rhOptions )
  1986. The C<Open> method opens a Registry key and returns a new
  1987. I<Win32::TieRegistry> object associated with that Registry key.
  1988. If C<Open> is called via a reference to a tied hash, then C<Open>
  1989. returns another reference to a tied hash. Otherwise C<Open>
  1990. returns a simple object and you should then use C<TiedRef> to get
  1991. a reference to a tied hash.
  1992. C<$sSubKey> is a string specifying a subkey to be opened.
  1993. Alternately C<$sSubKey> can be a reference to an array value
  1994. containing the list of increasingly deep subkeys specifying the
  1995. path to the subkey to be opened.
  1996. C<$rhOptions> is an optional reference to a hash containing extra
  1997. options. The C<Open> method supports two options, C<"Delimiter">
  1998. and C<"Access">, and C<$rhOptions> should have only have zero or
  1999. more of these strings as keys. See the "Examples" section below
  2000. for more information.
  2001. The C<"Delimiter"> option specifies what string [usually a single
  2002. character] will be used as the delimiter to be appended to subkey
  2003. names and prepended to value names. If this option is not specified,
  2004. the new key [C<$subKey>] inherits the delimiter of the old key
  2005. [C<$key>].
  2006. The C<"Access"> option specifies what level of access to the
  2007. Registry key you wish to have once it has been opened. If this
  2008. option is not specified, the new key [C<$subKey>] is opened with
  2009. the same access level used when the old key [C<$key>] was opened.
  2010. The virtual root of the Registry pretends it was opened with
  2011. access C<KEY_READ|KEY_WRITE> so this is the default access when
  2012. opening keys directory via C<$Registry>. If you don't plan on
  2013. modifying a key, you should open it with C<KEY_READ> access as
  2014. you may not have C<KEY_WRITE> access to it or some of its subkeys.
  2015. If the C<"Access"> option value is a string that starts with
  2016. C<"KEY_">, then it should match E<one> of the predefined access
  2017. levels [probably C<"KEY_READ">, C<"KEY_WRITE">, or
  2018. C<"KEY_ALL_ACCESS">] exported by the C<Win32API::Registry> module.
  2019. Otherwise, a numeric value is expected. For maximum flexibility,
  2020. include C<use Win32API::Registry qw(:KEY_);>, for example, near
  2021. the top of your script so you can specify more complicated access
  2022. levels such as C<KEY_READ|KEY_WRITE>.
  2023. If C<$sSubKey> does not begin with the delimiter [or C<$sSubKey>
  2024. is an array reference], then the path to the subkey to be opened
  2025. will be relative to the path of the original key [C<$key>]. If
  2026. C<$sSubKey> begins with a single delimiter, then the path to the
  2027. subkey to be opened will be relative to the virtual root of the
  2028. Registry on whichever machine the original key resides. If
  2029. C<$sSubKey> begins with two consectutive delimiters, then those
  2030. must be followed by a machine name which causes the C<Connect()>
  2031. method function to be called.
  2032. Examples:
  2033. $machKey= $Registry->Open( "LMachine", {Access=>KEY_READ,Delimiter=>"/"} )
  2034. or die "Can't open HKEY_LOCAL_MACHINE key: $^E\n";
  2035. $swKey= $machKey->Open( "Software" );
  2036. $logonKey= $swKey->Open( "Microsoft/Windows NT/CurrentVersion/Winlogon/" );
  2037. $NTversKey= $swKey->Open( ["Microsoft","Windows NT","CurrentVersion"] );
  2038. $versKey= $swKey->Open( qw(Microsoft Windows CurrentVersion) );
  2039. $remoteKey= $Registry->Open( "//HostA/LMachine/System/", {Delimiter=>"/"} )
  2040. or die "Can't connect to HostA or can't open subkey: $^E\n";
  2041. =item Clone
  2042. =item $copy= $key->Clone
  2043. Creates a new object that is associated with the same Registry key
  2044. as the invoking object.
  2045. =item Connect
  2046. =item $remoteKey= $Registry->Connect( $sMachineName, $sKeyPath, $rhOptions )
  2047. The C<Connect> method connects to the Registry of a remote machine,
  2048. and opens a key within it, then returns a new I<Win32::TieRegistry>
  2049. object associated with that remote Registry key. If C<Connect>
  2050. was called using a reference to a tied hash, then the return value
  2051. will also be a reference to a tied hash [or C<undef>]. Otherwise,
  2052. if you wish to use the returned object as a tied hash [not just as
  2053. an object], then use the C<TiedRef> method function after C<Connect>.
  2054. C<$sMachineName> is the name of the remote machine. You don't have
  2055. to preceed the machine name with two delimiter characters.
  2056. C<$sKeyPath> is a string specifying the remote key to be opened.
  2057. Alternately C<$sKeyPath> can be a reference to an array value
  2058. containing the list of increasingly deep keys specifying the path
  2059. to the key to be opened.
  2060. C<$rhOptions> is an optional reference to a hash containing extra
  2061. options. The C<Connect> method supports two options, C<"Delimiter">
  2062. and C<"Access">. See the C<Open> method documentation for more
  2063. information on these options.
  2064. C<$sKeyPath> is already relative to the virtual root of the Registry
  2065. of the remote machine. A single leading delimiter on C<sKeyPath>
  2066. will be ignored and is not required.
  2067. C<$sKeyPath> can be empty in which case C<Connect> will return an
  2068. object representing the virtual root key of the remote Registry.
  2069. Each subsequent use of C<Open> on this virtual root key will call
  2070. the system C<RegConnectRegistry> function.
  2071. The C<Connect> method can be called via any I<Win32::TieRegistry>
  2072. object, not just C<$Registry>. Attributes such as the desired
  2073. level of access and the delimiter will be inherited from the
  2074. object used but the C<$sKeyPath> will always be relative to the
  2075. virtual root of the remote machine's registry.
  2076. Examples:
  2077. $remMachKey= $Registry->Connect( "HostA", "LMachine", {Delimiter->"/"} )
  2078. or die "Can't connect to HostA's HKEY_LOCAL_MACHINE key: $^E\n";
  2079. $remVersKey= $remMachKey->Connect( "www.microsoft.com",
  2080. "LMachine/Software/Microsoft/Inetsrv/CurrentVersion/",
  2081. { Access->KEY_READ, Delimiter->"/" } )
  2082. or die "Can't check what version of IIS Microsoft is running: $^E\n";
  2083. $remVersKey= $remMachKey->Connect( "www",
  2084. qw(LMachine Software Microsoft Inetsrv CurrentVersion) )
  2085. or die "Can't check what version of IIS we are running: $^E\n";
  2086. =item ObjectRef
  2087. =item $object_ref= $obj_or_hash_ref->ObjectRef
  2088. For a simple object, just returns itself [C<$obj == $obj->ObjectRef>].
  2089. For a reference to a tied hash [if it is also an object], C<ObjectRef>
  2090. returns the simple object that the hash is tied to.
  2091. This is primarilly useful when debugging since typing C<x $Registry>
  2092. will try to display your I<entire> registry contents to your screen.
  2093. But the debugger command C<x $Registry->ObjectRef> will just dump
  2094. the implementation details of the underlying object to your screen.
  2095. =item Flush( $bFlush )
  2096. Flushes all cached information about the Registry key so that future
  2097. uses will get fresh data from the Registry.
  2098. If the optional C<$bFlush> is specified and a true value, then
  2099. C<RegFlushKey()> will be called, which is almost never necessary.
  2100. =item GetValue
  2101. =item $ValueData= $key->GetValue( $sValueName )
  2102. =item ($ValueData,$ValueType)= $key->GetValue( $sValueName )
  2103. Gets a Registry value's data and data type.
  2104. C<$ValueData> is usually just a Perl string that contains the
  2105. value data [packed into it]. For certain types of data, however,
  2106. C<$ValueData> may be processed as described below.
  2107. C<$ValueType> is the C<REG_*> constant describing the type of value
  2108. data stored in C<$ValueData>. If the C<DualTypes()> option is on,
  2109. then C<$ValueType> will be a dual value. That is, when used in a
  2110. numeric context, C<$ValueType> will give the numeric value of a
  2111. C<REG_*> constant. However, when used in a non-numeric context,
  2112. C<$ValueType> will return the name of the C<REG_*> constant, for
  2113. example C<"REG_SZ"> [note the quotes]. So both of the following
  2114. can be true at the same time:
  2115. $ValueType == REG_SZ
  2116. and
  2117. $ValueType eq "REG_SZ"
  2118. =over
  2119. =item REG_SZ and REG_EXPAND_SZ
  2120. If the C<FixSzNulls()> option is on, then the trailing C<'\0'> will be
  2121. stripped [unless there isn't one] before values of type C<REG_SZ>
  2122. and C<REG_EXPAND_SZ> are returned. Note that C<SetValue()> will add
  2123. a trailing C<'\0'> under similar circumstances.
  2124. =item REG_MULTI_SZ
  2125. If the C<SplitMultis()> option is on, then values of this type are
  2126. returned as a reference to an array containing the strings. For
  2127. example, a value that, with C<SplitMultis()> off, would be returned as:
  2128. "Value1\000Value2\000\000"
  2129. would be returned, with C<SplitMultis()> on, as:
  2130. [ "Value1", "Value2" ]
  2131. =item REG_DWORD
  2132. If the C<DualBinVals()> option is on, then the value is returned
  2133. as a scalar containing both a string and a number [much like
  2134. the C<$!> variable -- see the C<SetDualVar()> module for more
  2135. information] where the number part is the "unpacked" value.
  2136. Use the returned value in a numeric context to access this part
  2137. of the value. For example:
  2138. $num= 0 + $Registry->{"CUser/Console//ColorTable01"};
  2139. If the C<DWordsToHex()> option is off, the string part of the
  2140. returned value is a packed, 4-byte string [use C<unpack("L",$value)>
  2141. to get the numeric value.
  2142. If C<DWordsToHex()> is on, the string part of the returned value is
  2143. a 10-character hex strings [with leading "0x"]. You can use
  2144. C<hex($value)> to get the numeric value.
  2145. Note that C<SetValue()> will properly understand each of these
  2146. returned value formats no matter how C<DualBinVals()> is set.
  2147. =back
  2148. =item ValueNames
  2149. =item @names= $key->ValueNames
  2150. Returns the list of value names stored directly in a Registry key.
  2151. Note that the names returned do I<not> have a delimiter prepended
  2152. to them like with C<MemberNames()> and tied hashes.
  2153. Once you request this information, it is cached in the object and
  2154. future requests will always return the same list unless C<Flush()>
  2155. has been called.
  2156. =item SubKeyNames
  2157. =item @key_names= $key->SubKeyNames
  2158. Returns the list of subkey names stored directly in a Registry key.
  2159. Note that the names returned do I<not> have a delimiter appended
  2160. to them like with C<MemberNames()> and tied hashes.
  2161. Once you request this information, it is cached in the object and
  2162. future requests will always return the same list unless C<Flush()>
  2163. has been called.
  2164. =item SubKeyClasses
  2165. =item @classes= $key->SubKeyClasses
  2166. Returns the list of classes for subkeys stored directly in a
  2167. Registry key. The classes are returned in the same order as
  2168. the subkey names returned by C<SubKeyNames()>.
  2169. =item SubKeyTimes
  2170. =item @times= $key->SubKeyTimes
  2171. Returns the list of last-modified times for subkeys stored
  2172. directly in a Registry key. The times are returned in the same
  2173. order as the subkey names returned by C<SubKeyNames()>. Each
  2174. time is a C<FILETIME> structure packed into a Perl string.
  2175. Once you request this information, it is cached in the object and
  2176. future requests will always return the same list unless C<Flush()>
  2177. has been called.
  2178. =item MemberNames
  2179. =item @members= $key->MemberNames
  2180. Returns the list of subkey names and value names stored directly
  2181. in a Registry key. Subkey names have a delimiter appended to the
  2182. end and value names have a delimiter prepended to the front.
  2183. Note that a value name could end in a delimiter [or could be C<"">
  2184. so that the member name returned is just a delimiter] so the
  2185. presence or absence of the leading delimiter is what should be
  2186. used to determine whether a particular name is for a subkey or a
  2187. value, not the presence or absence of a trailing delimiter.
  2188. Once you request this information, it is cached in the object and
  2189. future requests will always return the same list unless C<Flush()>
  2190. has been called.
  2191. =item Information
  2192. =item %info= $key->Information
  2193. =item @items= $key->Information( @itemNames );
  2194. Returns the following information about a Registry key:
  2195. =over
  2196. =item LastWrite
  2197. A C<FILETIME> structure indicating when the key was last modified
  2198. and packed into a Perl string.
  2199. =item CntSubKeys
  2200. The number of subkeys stored directly in this key.
  2201. =item CntValues
  2202. The number of values stored directly in this key.
  2203. =item SecurityLen
  2204. The length [in bytes] of the largest[?] C<SECURITY_DESCRIPTOR>
  2205. associated with the Registry key.
  2206. =item MaxValDataLen
  2207. The length [in bytes] of the longest value data associated with
  2208. a value stored in this key.
  2209. =item MaxSubKeyLen
  2210. The length [in chars] of the longest subkey name associated with
  2211. a subkey stored in this key.
  2212. =item MaxSubClassLen
  2213. The length [in chars] of the longest class name associated with
  2214. a subkey stored directly in this key.
  2215. =item MaxValNameLen
  2216. The length [in chars] of the longest value name associated with
  2217. a value stored in this key.
  2218. =back
  2219. With no arguments, returns a hash [not a reference to a hash] where
  2220. the keys are the names for the items given above and the values
  2221. are the information describe above. For example:
  2222. %info= ( "CntValues" => 25, # Key contains 25 values.
  2223. "MaxValNameLen" => 20, # One of which has a 20-char name.
  2224. "MaxValDataLen" => 42, # One of which has a 42-byte value.
  2225. "CntSubKeys" => 1, # Key has 1 immediate subkey.
  2226. "MaxSubKeyLen" => 13, # One of which has a 12-char name.
  2227. "MaxSubClassLen" => 0, # All of which have class names of "".
  2228. "SecurityLen" => 232, # One SECURITY_DESCRIPTOR is 232 bytes.
  2229. "LastWrite" => "\x90mZ\cX{\xA3\xBD\cA\c@\cA"
  2230. # Key was last modifed 1998/06/01 16:29:32 GMT
  2231. );
  2232. With arguments, each one must be the name of a item given above.
  2233. The return value is the information associated with the listed
  2234. names. In other words:
  2235. return $key->Information( @names );
  2236. returns the same list as:
  2237. %info= $key->Information;
  2238. return @info{@names};
  2239. =item Delimiter
  2240. =item $oldDelim= $key->Delimiter
  2241. =item $oldDelim= $key->Delimiter( $newDelim )
  2242. Gets and possibly changes the delimiter used for this object. The
  2243. delimiter is appended to subkey names and prepended to value names
  2244. in many return values. It is also used when parsing keys passed
  2245. to tied hashes.
  2246. The delimiter defaults to backslash (C<'\\'>) but is inherited from
  2247. the object used to create a new object and can be specified by an
  2248. option when a new object is created.
  2249. =item Handle
  2250. =item $handle= $key->Handle
  2251. Returns the raw C<HKEY> handle for the associated Registry key as
  2252. an integer value. This value can then be used to Reg*() calls
  2253. from C<Win32API::Registry>. However, it is usually easier to just
  2254. call the C<Win32API::Registry> calls directly via:
  2255. $key->RegNotifyChangeKeyValue( ... );
  2256. For the virtual root of the local or a remote Registry,
  2257. C<Handle()> return C<"NONE">.
  2258. =item Path
  2259. =item $path= $key->Path
  2260. Returns a string describing the path of key names to this
  2261. Registry key. The string is built so that if it were passed
  2262. to C<$Registry->Open()>, it would reopen the same Registry key
  2263. [except in the rare case where one of the key names contains
  2264. C<$key->Delimiter>].
  2265. =item Machine
  2266. =item $computerName= $key->Machine
  2267. Returns the name of the computer [or "machine"] on which this Registry
  2268. key resides. Returns C<""> for local Registry keys.
  2269. =item Access
  2270. Returns the numeric value of the bit mask used to specify the
  2271. types of access requested when this Registry key was opened. Can
  2272. be compared to C<KEY_*> values.
  2273. =item OS_Delimiter
  2274. Returns the delimiter used by the operating system's RegOpenKeyEx()
  2275. call. For Win32, this is always backslash (C<"\\">).
  2276. =item Roots
  2277. Returns the mapping from root key names like C<"LMachine"> to their
  2278. associated C<HKEY_*> constants. Primarily for internal use and
  2279. subject to change.
  2280. =item Tie
  2281. =item $key->Tie( \%hash );
  2282. Ties the referenced hash to that Registry key. Pretty much the
  2283. same as
  2284. tie %hash, ref($key), $key;
  2285. Since C<ref($key)> is the class [package] to tie the hash to and
  2286. C<TIEHASH()> just returns its argument, C<$key>, [without calling
  2287. C<new()>] when it sees that it is already a blessed object.
  2288. =item TiedRef
  2289. =item $TiedHashRef= $hash_or_obj_ref->TiedRef
  2290. For a simple object, returns a reference to a hash tied to the
  2291. object. Used to promote a simple object into a combined object
  2292. and hash ref.
  2293. If already a reference to a tied hash [that is also an object],
  2294. it just returns itself [C<$ref == $ref->TiedRef>].
  2295. Mostly used internally.
  2296. =item ArrayValues
  2297. =item $oldBool= $key->ArrayValues
  2298. =item $oldBool= $key->ArrayValues( $newBool )
  2299. Gets the current setting of the C<ArrayValues> option and possibly
  2300. turns it on or off.
  2301. When off, Registry values fetched via a tied hash are returned as
  2302. just a value scalar [the same as C<GetValue()> in a scalar context].
  2303. When on, they are returned as a reference to an array containing
  2304. the value data as the C<[0]> element and the data type as the C<[1]>
  2305. element.
  2306. =item TieValues
  2307. =item $oldBool= TieValues
  2308. =item $oldBool= TieValues( $newBool )
  2309. Gets the current setting of the C<TieValues> option and possibly
  2310. turns it on or off.
  2311. Turning this option on is not yet supported in this release of
  2312. C<Win32::TieRegistry>. In a future release, turning this option
  2313. on will cause Registry values returned from a tied hash to be
  2314. a tied array that you can use to modify the value in the Registry.
  2315. =item FastDelete
  2316. =item $oldBool= $key->FastDelete
  2317. =item $oldBool= $key->FastDelete( $newBool )
  2318. Gets the current setting of the C<FastDelete> option and possibly
  2319. turns it on or off.
  2320. When on, successfully deleting a Registry key [via a tied hash]
  2321. simply returns C<1>.
  2322. When off, successfully deleting a Registry key [via a tied hash
  2323. and not in a void context] returns a reference to a hash that
  2324. contains the values present in the key when it was deleted. This
  2325. hash is just like that returned when referencing the key before it
  2326. was deleted except that it is an ordinary hash, not one tied to
  2327. the C<Win32::TieRegistry> package.
  2328. Note that deleting either a Registry key or value via a tied hash
  2329. I<in a void context> prevents any overhead in trying to build an
  2330. appropriate return value.
  2331. Note that deleting a Registry I<value> via a tied hash [not in
  2332. a void context] returns the value data even if <FastDelete> is on.
  2333. =item SplitMultis
  2334. =item $oldBool= $key->SplitMultis
  2335. =item $oldBool= $key->SplitMultis( $newBool )
  2336. Gets the current setting of the C<SplitMultis> option and possibly
  2337. turns it on or off.
  2338. If on, Registry values of type C<REG_MULTI_SZ> are returned as
  2339. a reference to an array of strings. See C<GetValue()> for more
  2340. information.
  2341. =item DWordsToHex
  2342. =item $oldBool= $key->DWordsToHex
  2343. =item $oldBool= $key->DWordsToHex( $newBool )
  2344. Gets the current setting of the C<DWordsToHex> option and possibly
  2345. turns it on or off.
  2346. If on, Registry values of type C<REG_DWORD> are returned as a hex
  2347. string with leading C<"0x"> and longer than 4 characters. See
  2348. C<GetValue()> for more information.
  2349. =item FixSzNulls
  2350. =item $oldBool= $key->FixSzNulls
  2351. =item $oldBool= $key->FixSzNulls( $newBool )
  2352. Gets the current setting of the C<FixSzNulls> option and possibly
  2353. turns it on or off.
  2354. If on, Registry values of type C<REG_SZ> and C<REG_EXPAND_SZ> have
  2355. trailing C<'\0'>s added before they are set and stripped before
  2356. they are returned. See C<GetValue()> and C<SetValue()> for more
  2357. information.
  2358. =item DualTypes
  2359. =item $oldBool= $key->DualTypes
  2360. =item $oldBool= $key->DualTypes( $newBool )
  2361. Gets the current setting of the C<DualTypes> option and possibly
  2362. turns it on or off.
  2363. If on, data types are returned as a combined numeric/string value
  2364. holding both the numeric value of a C<REG_*> constant and the
  2365. string value of the constant's name. See C<GetValue()> for
  2366. more information.
  2367. =item DualBinVals
  2368. =item $oldBool= $key->DualBinVals
  2369. =item $oldBool= $key->DualBinVals( $newBool )
  2370. Gets the current setting of the C<DualBinVals> option and possibly
  2371. turns it on or off.
  2372. If on, Registry value data of type C<REG_BINARY> and no more than
  2373. 4 bytes long and Registry values of type C<REG_DWORD> are returned
  2374. as a combined numeric/string value where the numeric value is the
  2375. "unpacked" binary value as returned by:
  2376. hex reverse unpack( "h*", $valData )
  2377. on a "little-endian" computer. [Would be C<hex unpack("H*",$valData)>
  2378. on a "big-endian" computer if this module is ever ported to one.]
  2379. See C<GetValue()> for more information.
  2380. =item GetOptions
  2381. =item @oldOpts= $key->GetOptions( @optionNames )
  2382. Returns the current setting of any of the following options:
  2383. Delimiter FixSzNulls DWordsToHex
  2384. ArrayValues SplitMultis DualBinVals
  2385. TieValues FastDelete DualTypes
  2386. =item SetOptions
  2387. =item @oldOpts= $key->SetOptions( optNames=>$optValue,... )
  2388. Changes the current setting of any of the following options,
  2389. returning the previous setting(s):
  2390. Delimiter FixSzNulls DWordsToHex AllowLoad
  2391. ArrayValues SplitMultis DualBinVals AllowSave
  2392. TieValues FastDelete DualTypes
  2393. For C<AllowLoad> and C<AllowSave>, instead of the previous
  2394. setting, C<SetOptions> returns whether or not the change was
  2395. successful.
  2396. In a scalar context, returns only the last item. The last
  2397. option can also be specified as C<"ref"> or C<"r"> [which doesn't
  2398. need to be followed by a value] to allow chaining:
  2399. $key->SetOptions(AllowSave=>1,"ref")->RegSaveKey(...)
  2400. =item SetValue
  2401. =item $okay= $key->SetValue( $ValueName, $ValueData );
  2402. =item $okay= $key->SetValue( $ValueName, $ValueData, $ValueType );
  2403. Adds or replaces a Registry value. Returns a true value if
  2404. successfully, false otherwise.
  2405. C<$ValueName> is the name of the value to add or replace and
  2406. should I<not> have a delimiter prepended to it. Case is ignored.
  2407. C<$ValueType> is assumed to be C<REG_SZ> if it is omitted. Otherwise,
  2408. it should be one the C<REG_*> constants.
  2409. C<$ValueData> is the data to be stored in the value, probably packed
  2410. into a Perl string. Other supported formats for value data are
  2411. listed below for each posible C<$ValueType>.
  2412. =over
  2413. =item REG_SZ or REG_EXPAND_SZ
  2414. The only special processing for these values is the addition of
  2415. the required trailing C<'\0'> if it is missing. This can be
  2416. turned off by disabling the C<FixSzNulls> option.
  2417. =item REG_MULTI_SZ
  2418. These values can also be specified as a reference to a list of
  2419. strings. For example, the following two lines are equivalent:
  2420. $key->SetValue( "Val1\000Value2\000LastVal\000\000", REG_MULTI_SZ );
  2421. vs.
  2422. $key->SetValue( ["Val1","Value2","LastVal"], REG_MULTI_SZ );
  2423. Note that if the required two trailing nulls (C<"\000\000">) are
  2424. missing, then this release of C<SetValue()> will I<not> add them.
  2425. =item REG_DWORD
  2426. These values can also be specified as a hex value with the leading
  2427. C<"0x"> included and totaling I<more than> 4 bytes. These will be
  2428. packed into a 4-byte string via:
  2429. $data= pack( "L", hex($data) );
  2430. =item REG_BINARY
  2431. This value type is listed just to emphasize that no alternate
  2432. format is supported for it. In particular, you should I<not> pass
  2433. in a numeric value for this type of data. C<SetValue()> cannot
  2434. distinguish such from a packed string that just happens to match
  2435. a numeric value and so will treat it as a packed string.
  2436. =back
  2437. An alternate calling format:
  2438. $okay= $key->SetValue( $ValueName, [ $ValueData, $ValueType ] );
  2439. [two arguments, the second of which is a reference to an array
  2440. containing the value data and value type] is supported to ease
  2441. using tied hashes with C<SetValue()>.
  2442. =item CreateKey
  2443. =item $newKey= $key->CreateKey( $subKey );
  2444. =item $newKey= $key->CreateKey( $subKey, { Option=>OptVal,... } );
  2445. Creates a Registry key or just updates attributes of one. Calls
  2446. C<RegCreateKeyEx()> then, if it succeeded, creates an object
  2447. associated with the [possibly new] subkey.
  2448. C<$subKey> is the name of a subkey [or a path to one] to be
  2449. created or updated. It can also be a reference to an array
  2450. containing a list of subkey names.
  2451. The second argument, if it exists, should be a reference to a
  2452. hash specifying options either to be passed to C<RegCreateKeyEx()>
  2453. or to be used when creating the associated object. The following
  2454. items are the supported keys for this options hash:
  2455. =over
  2456. =item Delimiter
  2457. Specifies the delimiter to be used to parse C<$subKey> and to be
  2458. used in the new object. Defaults to C<$key->Delimiter>.
  2459. =item Access
  2460. Specifies the types of access requested when the subkey is opened.
  2461. Should be a numeric bit mask that combines one or more C<KEY_*>
  2462. constant values.
  2463. =item Class
  2464. The name to assign as the class of the new or updated subkey.
  2465. Defaults to C<""> as we have never seen a use for this information.
  2466. =item Disposition
  2467. Lets you specify a reference to a scalar where, upon success,
  2468. either C<REG_CREATED_NEW_KEY> or C<REG_OPENED_EXISTING_KEY>
  2469. depending on whether a new key was created or an existing key
  2470. was opened.
  2471. =item Security
  2472. Lets you specify a C<SECURITY_ATTRIBUTES> structure packed into a
  2473. Perl string. See C<Win32API::Registry::RegCreateKeyEx()> for more
  2474. information.
  2475. =item Volatile
  2476. If true, specifies that the new key should be volatile, that is,
  2477. stored only in memory and not backed by a hive file [and not saved
  2478. if the computer is rebooted]. This option is ignored under
  2479. Windows 95. Specifying C<Volatile=E<GT>1> is the same as
  2480. specifying C<Options=E<GT>REG_OPTION_VOLATILE>.
  2481. =item Backup
  2482. If true, specifies that the new key should be opened for
  2483. backup/restore access. The C<Access> option is ignored. If the
  2484. calling process has enabled C<"SeBackupPrivilege">, then the
  2485. subkey is opened with C<KEY_READ> access as the C<"LocalSystem">
  2486. user which should have access to all subkeys. If the calling
  2487. process has enabled C<"SeRestorePrivilege">, then the subkey is
  2488. opened with C<KEY_WRITE> access as the C<"LocalSystem"> user which
  2489. should have access to all subkeys.
  2490. This option is ignored under Windows 95. Specifying C<Backup=E<GT>1>
  2491. is the same as specifying C<Options=E<GT>REG_OPTION_BACKUP_RESTORE>.
  2492. =item Options
  2493. Lets you specify options to the C<RegOpenKeyEx()> call. The value
  2494. for this option should be a numeric value combining zero or more
  2495. of the C<REG_OPTION_*> bit masks. You may with to used the
  2496. C<Volatile> and/or C<Backup> options instead of this one.
  2497. =back
  2498. =item StoreKey
  2499. =item $newKey= $key->StoreKey( $subKey, \%Contents );
  2500. Primarily for internal use.
  2501. Used to create or update a Registry key and any number of subkeys
  2502. or values under it or its subkeys.
  2503. C<$subKey> is the name of a subkey to be created [or a path of
  2504. subkey names separated by delimiters]. If that subkey already
  2505. exists, then it is updated.
  2506. C<\%Contents> is a reference to a hash containing pairs of
  2507. value names with value data and/or subkey names with hash
  2508. references similar to C<\%Contents>. Each of these cause
  2509. a value or subkey of C<$subKey> to be created or updated.
  2510. If C<$Contents{""}> exists and is a reference to a hash, then
  2511. it used as the options argument when C<CreateKey()> is called
  2512. for C<$subKey>. This allows you to specify ...
  2513. if( defined( $$data{""} ) && "HASH" eq ref($$data{""}) ) {
  2514. $self= $this->CreateKey( $subKey, delete $$data{""} );
  2515. =item Load
  2516. =item $newKey= $key->Load( $file )
  2517. =item $newKey= $key->Load( $file, $newSubKey )
  2518. =item $newKey= $key->Load( $file, $newSubKey, { Option=>OptVal... } )
  2519. =item $newKey= $key->Load( $file, { Option=>OptVal... } )
  2520. Loads a hive file into a Registry. That is, creates a new subkey
  2521. and associates a hive file with it.
  2522. C<$file> is a hive file, that is a file created by calling
  2523. C<RegSaveKey()>. The C<$file> path is interpreted relative to
  2524. C<%SystemRoot%/System32/config> on the machine where C<$key>
  2525. resides.
  2526. C<$newSubKey> is the name to be given to the new subkey. If
  2527. C<$newSubKey> is specified, then C<$key> must be
  2528. C<HKEY_LOCAL_MACHINE> or C<HKEY_USERS> of the local computer
  2529. or a remote computer and C<$newSubKey> should not contain any
  2530. occurrences of either the delimiter or the OS delimiter.
  2531. If C<$newSubKey> is not specified, then it is as if C<$key>
  2532. was C<$Registry-E<GT>{LMachine}> and C<$newSubKey> is
  2533. C<"PerlTie:999"> where C<"999"> is actually a sequence number
  2534. incremented each time this process calls C<Load()>.
  2535. You can specify as the last argument a reference to a hash
  2536. containing options. You can specify the same options that you
  2537. can specify to C<Open()>. See C<Open()> for more information on
  2538. those. In addition, you can specify the option C<"NewSubKey">.
  2539. The value of this option is interpretted exactly as if it was
  2540. specified as the C<$newSubKey> parameter and overrides the
  2541. C<$newSubKey> if one was specified.
  2542. =item UnLoad
  2543. =item $okay= $key->UnLoad
  2544. Unloads a hive that was loaded via C<Load()>. Cannot unload other
  2545. hives. C<$key> must be the return from a previous call to C<Load()>.
  2546. C<$key> is closed and then the hive is unloaded.
  2547. =item AllowSave
  2548. =item $okay= AllowSave( $bool )
  2549. Enables or disables the C<"ReBackupPrivilege"> privilege for the
  2550. current process. You will probably have to enable this privilege
  2551. before you can use C<RegSaveKey()>.
  2552. The return value indicates whether the operation succeeded, not
  2553. whether the privilege was previously enabled.
  2554. =item AllowLoad
  2555. =item $okay= AllowLoad( $bool )
  2556. Enables or disables the C<"ReRestorePrivilege"> privilege for the
  2557. current process. You will probably have to enable this privilege
  2558. before you can use C<RegLoadKey()>, C<RegUnLoadKey()>,
  2559. C<RegReplaceKey()>, or C<RegRestoreKey> and thus C<Load()> and
  2560. C<UnLoad()>.
  2561. The return value indicates whether the operation succeeded, not
  2562. whether the privilege was previously enabled.
  2563. =back
  2564. =head1 SUMMARY
  2565. Most things can be done most easily via tied hashes. Skip down to the
  2566. the L<Tied Hashes Summary> to get started quickly.
  2567. =head2 Objects Summary
  2568. Here are quick examples that document the most common functionality
  2569. of all of the method functions [except for a few almost useless ones].
  2570. # Just another way of saying Open():
  2571. $key= new Win32::TieRegistry "LMachine\\Software\\",
  2572. { Access=>KEY_READ|KEY_WRITE, Delimiter=>"\\" };
  2573. # Open a Registry key:
  2574. $subKey= $key->Open( "SubKey/SubSubKey/",
  2575. { Access=>KEY_ALL_ACCESS, Delimiter=>"/" } );
  2576. # Connect to a remote Registry key:
  2577. $remKey= $Registry->Connect( "MachineName", "LMachine/",
  2578. { Access=>KEY_READ, Delimiter=>"/" } );
  2579. # Get value data:
  2580. $valueString= $key->GetValue("ValueName");
  2581. ( $valueString, $valueType )= $key->GetValue("ValueName");
  2582. # Get list of value names:
  2583. @valueNames= $key->ValueNames;
  2584. # Get list of subkey names:
  2585. @subKeyNames= $key->SubKeyNames;
  2586. # Get combined list of value names (with leading delimiters)
  2587. # and subkey names (with trailing delimiters):
  2588. @memberNames= $key->MemberNames;
  2589. # Get all information about a key:
  2590. %keyInfo= $key->Information;
  2591. # keys(%keyInfo)= qw( Class LastWrite SecurityLen
  2592. # CntSubKeys MaxSubKeyLen MaxSubClassLen
  2593. # CntValues MaxValNameLen MaxValDataLen );
  2594. # Get selected information about a key:
  2595. ( $class, $cntSubKeys )= $key->Information( "Class", "CntSubKeys" );
  2596. # Get and/or set delimiter:
  2597. $delim= $key->Delimiter;
  2598. $oldDelim= $key->Delimiter( $newDelim );
  2599. # Get "path" for an open key:
  2600. $path= $key->Path;
  2601. # For example, "/CUser/Control Panel/Mouse/"
  2602. # or "//HostName/LMachine/System/DISK/".
  2603. # Get name of machine where key is from:
  2604. $mach= $key->Machine;
  2605. # Will usually be "" indicating key is on local machine.
  2606. # Control different options (see main documentation for descriptions):
  2607. $oldBool= $key->ArrayValues( $newBool );
  2608. $oldBool= $key->FastDelete( $newBool );
  2609. $oldBool= $key->FixSzNulls( $newBool );
  2610. $oldBool= $key->SplitMultis( $newBool );
  2611. $oldBool= $key->DWordsToHex( $newBool );
  2612. $oldBool= $key->DualBinVals( $newBool );
  2613. $oldBool= $key->DualTypes( $newBool );
  2614. @oldBools= $key->SetOptions( ArrayValues=>1, FastDelete=>1, FixSzNulls=>0,
  2615. Delimiter=>"/", AllowLoad=>1, AllowSave=>1 );
  2616. @oldBools= $key->GetOptions( ArrayValues, FastDelete, FixSzNulls );
  2617. # Add or set a value:
  2618. $key->SetValue( "ValueName", $valueDataString );
  2619. $key->SetValue( "ValueName", pack($format,$valueData), "REG_BINARY" );
  2620. # Add or set a key:
  2621. $key->CreateKey( "SubKeyName" );
  2622. $key->CreateKey( "SubKeyName",
  2623. { Access=>"KEY_ALL_ACCESS", Class=>"ClassName",
  2624. Delimiter=>"/", Volatile=>1, Backup=>1 } );
  2625. # Load an off-line Registry hive file into the on-line Registry:
  2626. $newKey= $Registry->Load( "C:/Path/To/Hive/FileName" );
  2627. $newKey= $key->Load( "C:/Path/To/Hive/FileName", "NewSubKeyName",
  2628. { Access=>KEY_READ } );
  2629. # Unload a Registry hive file loaded via the Load() method:
  2630. $newKey->UnLoad;
  2631. # (Dis)Allow yourself to load Registry hive files:
  2632. $success= $Registry->AllowLoad( $bool );
  2633. # (Dis)Allow yourself to save a Registry key to a hive file:
  2634. $success= $Registry->AllowSave( $bool );
  2635. # Save a Registry key to a new hive file:
  2636. $key->RegSaveKey( "C:/Path/To/Hive/FileName", [] );
  2637. =head3 Other Useful Methods
  2638. See C<Win32API::Registry> for more information on these methods.
  2639. These methods are provided for coding convenience and are
  2640. identical to the C<Win32API::Registry> functions except that these
  2641. don't take a handle to a Registry key, instead getting the handle
  2642. from the invoking object [C<$key>].
  2643. $key->RegGetKeySecurity( $iSecInfo, $sSecDesc, $lenSecDesc );
  2644. $key->RegLoadKey( $sSubKeyName, $sPathToFile );
  2645. $key->RegNotifyChangeKeyValue(
  2646. $bWatchSubtree, $iNotifyFilter, $hEvent, $bAsync );
  2647. $key->RegQueryMultipleValues(
  2648. $structValueEnts, $cntValueEnts, $Buffer, $lenBuffer );
  2649. $key->RegReplaceKey( $sSubKeyName, $sPathToNewFile, $sPathToBackupFile );
  2650. $key->RegRestoreKey( $sPathToFile, $iFlags );
  2651. $key->RegSetKeySecurity( $iSecInfo, $sSecDesc );
  2652. $key->RegUnLoadKey( $sSubKeyName );
  2653. =head2 Tied Hashes Summary
  2654. For fast learners, this may be the only section you need to read.
  2655. Always append one delimiter to the end of each Registry key name
  2656. and prepend one delimiter to the front of each Registry value name.
  2657. =head3 Opening keys
  2658. use Win32::TieRegistry ( Delimiter=>"/", ArrayValues=>1 );
  2659. $Registry->Delimiter("/"); # Set delimiter to "/".
  2660. $swKey= $Registry->{"LMachine/Software/"};
  2661. $winKey= $swKey->{"Microsoft/Windows/CurrentVersion/"};
  2662. $userKey= $Registry->
  2663. {"CUser/Software/Microsoft/Windows/CurrentVersion/"};
  2664. $remoteKey= $Registry->{"//HostName/LMachine/"};
  2665. =head3 Reading values
  2666. $progDir= $winKey->{"/ProgramFilesDir"}; # "C:\\Program Files"
  2667. $tip21= $winKey->{"Explorer/Tips//21"}; # Text of tip #21.
  2668. $winKey->ArrayValues(1);
  2669. ( $devPath, $type )= $winKey->{"/DevicePath"};
  2670. # $devPath eq "%SystemRoot%\\inf"
  2671. # $type eq "REG_EXPAND_SZ" [if you have SetDualVar.pm installed]
  2672. # $type == REG_EXPAND_SZ [if you did "use Win32API::Registry qw(REG_)"]
  2673. =head3 Setting values
  2674. $winKey->{"Setup//SourcePath"}= "\\\\SwServer\\SwShare\\Windows";
  2675. # Simple. Assumes data type of REG_SZ.
  2676. $winKey->{"Setup//Installation Sources"}=
  2677. [ "D:\x00\\\\SwServer\\SwShare\\Windows\0\0", "REG_MULTI_SZ" ];
  2678. # "\x00" and "\0" used to mark ends of each string and end of list.
  2679. $winKey->{"Setup//Installation Sources"}=
  2680. [ ["D:","\\\\SwServer\\SwShare\\Windows"], "REG_MULTI_SZ" ];
  2681. # Alternate method that is easier to read.
  2682. $userKey->{"Explorer/Tips//DisplayInitialTipWindow"}=
  2683. [ pack("L",0), "REG_DWORD" ];
  2684. $userKey->{"Explorer/Tips//Next"}= [ pack("S",3), "REG_BINARY" ];
  2685. $userKey->{"Explorer/Tips//Show"}= [ pack("L",0), "REG_BINARY" ];
  2686. =head3 Adding keys
  2687. $swKey->{"FooCorp/"}= {
  2688. "FooWriter/" => {
  2689. "/Version" => "4.032",
  2690. "Startup/" => {
  2691. "/Title" => "Foo Writer Deluxe ][",
  2692. "/WindowSize" => [ pack("LL",$wid,$ht), REG_BINARY ],
  2693. "/TaskBarIcon" => [ "0x0001", REG_DWORD ],
  2694. },
  2695. "Compatibility/" => {
  2696. "/AutoConvert" => "Always",
  2697. "/Default Palette" => "Windows Colors",
  2698. },
  2699. },
  2700. "/License", => "0123-9C8EF1-09-FC",
  2701. };
  2702. =head3 Listing all subkeys and values
  2703. @members= keys( %{$swKey} );
  2704. @subKeys= grep( m#^/#, keys( %{$swKey->{"Classes/batfile/"}} ) );
  2705. # @subKeys= ( "/", "/EditFlags" );
  2706. @valueNames= grep( ! m#^/#, keys( %{$swKey->{"Classes/batfile/"}} ) );
  2707. # @valueNames= ( "DefaultIcon/", "shell/", "shellex/" );
  2708. =head3 Deleting values or keys with no subkeys
  2709. $oldValue= delete $userKey->{"Explorer/Tips//Next"};
  2710. $oldValues= delete $userKey->{"Explorer/Tips/"};
  2711. # $oldValues will be reference to hash containing deleted keys values.
  2712. =head3 Closing keys
  2713. undef $swKey; # Explicit way to close a key.
  2714. $winKey= "Anything else"; # Implicitly closes a key.
  2715. exit 0; # Implicitly closes all keys.
  2716. =head2 Tie::Registry
  2717. This module was originally called C<Tie::Registry>. Changing code
  2718. that used C<Tie::Registry> over to C<Win32::TieRegistry> is trivial
  2719. as the module name should only be mentioned once, in the C<use>
  2720. line. However, finding all of the places that used C<Tie::Registry>
  2721. may not be completely trivial so we have included F<Tie/Registry.pm>
  2722. which you can install to provide backward compatibility.
  2723. =head1 AUTHOR
  2724. Tye McQueen, tye@metronet.com, see http://www.metronet.com/~tye/.
  2725. =head1 SEE ALSO
  2726. C<Win32API::Registry> - Provides access to Reg*(), HKEY_*,
  2727. KEY_*, REG_* [required].
  2728. C<Win32::WinError> - Defines ERROR_* values [optional].
  2729. C<SetDualVar> - For returning REG_* values as combined
  2730. string/integer [optional].
  2731. =head1 BUGS
  2732. Because I<Win32::TieRegistry> requires C<Win32API::Registry>
  2733. which uses the standard Perl tools for building extensions,
  2734. L<MakeMaker>, and these are not supported with the ActiveWare
  2735. versions of Perl, I<Win32::TieRegistry> cannot be used with the
  2736. ActiveWare versions of Perl. Sorry. The ActiveWare version and
  2737. standard version of Perl are merging so you may want to switch to
  2738. the standard version of Perl soon.
  2739. Because Perl hashes are case sensitive, certain lookups are also
  2740. case sensistive. In particular, the root keys ("Classes", "CUser",
  2741. "LMachine", "Users", "PerfData", "CConfig", "DynData", and HKEY_*)
  2742. must always be entered without changing between upper and lower
  2743. case letters. Also, the special rule for matching subkey names
  2744. that contain the user-selected delimiter only works if case is
  2745. matched. All other key name and value name lookups should be case
  2746. insensitive because the underlying Reg*() calls ignore case.
  2747. Perl5.004_02 has bugs that make Win32::TieRegistry fail in strange
  2748. and subtle ways.
  2749. Information about each key is cached when using a tied hash. A
  2750. future release should use C<RegNotifyChangeKeyValue()> to prevent
  2751. this cache from becoming out-of-date.
  2752. There is no test suite.
  2753. =cut
  2754. # Autoload not currently supported by Perl under Windows.