in reply to Re: while loop question
in thread while loop question

Thanks for the quick answer. nr.1 - copy-paste error. nr.2 - 100% RIGHT. nr.3 - understand. nr.4 - fast writing error :-) Sorry, code nr.4 is not good for "since you want to exit the loop when a certain key is reached" because I want to create a hash element if the has key is not there. For now I use the "defined" function (below) to do the work but I realy want to know if there is other solution.

unless ( defined $email{"email"} ) { $email{$html->param("email")}=$html->param("name"); }

Replies are listed 'Best First'.
Re^3: while loop question
by aitap (Curate) on Aug 21, 2014 at 11:48 UTC
    exists should help you with this problem. As you may have noticed, looping over keys of a hash is much slower than accessing it by key. By the way, very often it is plain wrong.

      "exisys" is not good for me at leat for this crrent problem because I use AnyDBM_File:

      AnyDBM_File doesn't define an EXISTS method at /gd/Development/Perl/Pr +actice/www/cgi-bin/submitcoffee.pl line 32.

        "EXISTS", "exisys" and "exists" are all different words.

        exists is not a method. It is a basic built-in perl function. It is completely and utterly unrelated to AnyDBM_File. It tells you if a key exists in a hash; that is what you want, no need for looping.

        Read the documentation linked by aitap for details.

        I can reproduce this error message: when I tie a hash using AnyDBM_File, it selects NDBM_File, which implements Tie::Hash without a sub EXISTS { ... }, so exists on the tied hash does not work.

        However, defined replaces exists in this case, because NDBM_File cannot store an undef in the database:

        #!/usr/bin/perl use Data::Dumper; use Fcntl; use AnyDBM_File; die $! unless tie %h, 'AnyDBM_File', 'test.db', O_RDWR()|O_CREAT(), 06 +00; undef $h{'b'}; # try to store an undef print Dumper(\%h); # empty string is stored instead print "still defined\n" if defined $h{'b'}; # we can confirm its existence: # if it's defined, it does exist # and no undefs exist there delete $h{'b'}; # delete works as expected print "does not exist\n" unless defined $h{'b'}; print Dumper(\%h); __END__ $VAR1 = { 'b' => '' }; still defined does not exist $VAR1 = {};
        So using defined turns out to be the right decision.