hesco has asked for the wisdom of the Perl Monks concerning the following question:

Hey folks: This one has me stumped. I've getting debugging output that looks like this:
$key is |dbhost| and $value is |localhost.localdomain| or |localhost.l +ocaldomain|. localhost.localdomain $key is |dbuser| and $value is |user| or |user|. user
but then:
Use of uninitialized value in string at ./cache-riding-pages.pl line 2 +6. Use of uninitialized value in string at ./cache-riding-pages.pl line 2 +7. Use of uninitialized value in string at ./cache-riding-pages.pl line 2 +8. Use of uninitialized value in string at ./cache-riding-pages.pl line 2 +9.
produced by code that looks something like:
#!/usr/bin/perl -w use strict; use DBI; my(%conf); my $config = "/path/to/conf/config.php"; my($dbh,$sql,$sth,$key,$value); open(CONF,$config); while (<CONF>) { if(m/\=/ && m/db/){ ($key,$value) = split(/ \= /,$_); chomp($key); chomp($value); $key =~ s/\$//; $value =~ s/\"//g; $value =~ s/\;//; $conf{'$key'} = $value; print "\$key is |$key| and \$value is |$value| or |$conf{'$key'}|. +\n"; print $conf{'$key'}; } } close CONF; # values %conf; # $dbh = ed_connect($conf{'dbhost'}, $conf{'dbname'}, $conf{'dbuser'}, + $conf{'dbpass'}); print "$conf{'dbhost'}"; print "$conf{'dbname'}"; print "$conf{'dbuser'}"; print "$conf{'dbpass'}"; # $dbh = connect('localhost', $conf{'dbname'}, $conf{'dbuser'}, $conf{ +'dbpass'}); exit; 1; sub ed_connect { my($host_name,$db_name,$db_user,$db_pass)=@_; my $dsn = "DBI:mysql:host=$host_name;database=$db_name"; return (DBI->connect($dsn,$db_user,$db_pass), {PrintError => 0, RaiseError => 1}); }
So my question is this: What happened to my %conf hash values when the CONF file handle got closed? All help is appreciated. Thank you for your time and consideration. -- Hugh

Replies are listed 'Best First'.
Re: Disappearing hash values
by william.ward (Novice) on Jan 21, 2006 at 19:01 UTC
    Try taking out the single quotes around $key when setting up the hash. When using single quotes around a variable name like '$key' the value returned is not the contents of $key but the characters '$', 'k', 'e', 'y' themselves. You could use double quotes but that is not necessary. Just use
        $conf{$key} = $value;
    and it should work.
      Thank you sir. I had been stumped by that one for a couple of hours. That moved me right along. your help is appreciated. Thanks. -- Hugh
Re: Disappearing hash values
by davidrw (Prior) on Jan 21, 2006 at 22:01 UTC
    printf (a personal preference to debug statement like this) and different quoting might have avoided confusion in this case:
    # print "\$key is |$key| and \$value is |$value| or |$conf{'$key'}|.\n +"; printf '$key is |%s| and $value is |%s| or |%s|'."\n", $key, $value, +$conf{$key};