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

Yes, I know someone just posted a "reading a DBM" question, but this is a little different than his problem. Actually, it makes me feel like a stupid n00b because I'm probably missing something really simple.

I am using the following code to read a list of names from a DBM file. All I want to do is see if a name exists in the list. As such, the DBM file Is just a name followed by the number 1 on each line. This is the code I use to check for a specific name:

#!/usr/bin/perl -w use strict; use DB_File; my %names; tie %names, 'DB_File', 'names.db' || die "$!"; print $names{'drew'}

Whenever I do that, I get "Use of uninitialized value in print." However, when I use the following code to iterate through the names, I get the entire list:

while(my ($key, $value) = each(%names)) { print "$key\t".$names{$key}."\n"; }

I know I'm doing something wrong, but I can't quite figure out what it is. Of course if there's an easier way to do this, I'd be glad to hear it too.

Replies are listed 'Best First'.
Re: Can't seem to read DBM
by moritz (Cardinal) on Sep 11, 2007 at 11:56 UTC
    The simplest explaination might be that there is no key drew in the hash, but others are.
      I have checked for the existence of the key. I've also tried it in both upper and lower case and I've tried numerous keys. I've also tried copying a key directly out of the DB file and into the code to eliminate any possibility of misspelling.
        dirtdart:

        You don't have any trailing spaces on your keys, do you? You might try modifying your dump to something like:

        while(my ($key, $value) = each(%names)) { print ".$key.\t".$names{$key}."\n"; }
        or use Data::Dumper or some such...

        ...roboticus

Re: Can't seem to read DBM
by SuicideJunkie (Vicar) on Sep 11, 2007 at 14:20 UTC

    Perhaps there is whitespace in your key names that is being hidden by the \t you're printing?

    Try using the loop to print "key='$key', value='$value'\n"; in order to make it perfectly clear.
      Thank you for the suggestions. I did, at one point, remove the tab character to check for trailing spaces and there were none.