Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

trying to implement hash table. and getting lots of difficulties. plz help me out..........

by Priti24 (Novice)
on Oct 10, 2012 at 05:38 UTC ( #998135=perlquestion: print w/ replies, xml ) Need Help??
Priti24 has asked for the wisdom of the Perl Monks concerning the following question:

i m new to perl. and i am trying to implement hash table . firstly i took a hash like

%ex = ( 37 => "p" , 41 => "t", 23 => "s" , 52 => "m", 44 => "a" , 65 => "q", 26 => "d" , 88 => "o" , 99 => "g" , 100 => "l" , 101 => "f" , 201 => "i" );

i also took an array with 10 ten empty buckets like

@buckets = ( [],[],[],[],[],[],[],[],[],[] );

after that i used a while loop and got key from there and after that i called a function perlhash to calculate the index of that key. after getting index of every particular key in hash , i pushed every key , value pair at index which i got from from perlhash function. if two keys having same index then it will store two keys at same index

sub perlhash { $hash = 0; $hash = ($k % 10); return $hash; } while(($k , $v) = each(%ex)) { $hash = perlhash($k); $ch = $buckets[$hash]; print Dumper $buckets[$hash]; if(scalar @{$ch} == 0){ $entry = {$k => $v}; }else{ $entry = $ch->[0]; $entry->{$k} = $v ; } push @$ch , $entry; } print Dumper @buckets;

now i want to search for a particular key existence and i want to get value for that key. how should i do that with my code.

print "enter a key u want to search"; $k = <STDIN>; $h = perlhash($k);

suppose i want to search 37. then this $h giving me index of 37. and through $buckets[$h] i can get value like.

my $VAR1 = [ { '37' => 't', } ];

how could i get 37 from this code. also if i search for 47 then this will also gave me same index then i have to apply a comparison that at this index 47 does not exist. and also how could i search 101 and its value here

firstly execute this code then u will understand in a better way

plz help me out from this problem

Comment on trying to implement hash table. and getting lots of difficulties. plz help me out..........
Select or Download Code
Re: trying to implement hash table. and getting lots of difficulties. plz help me out..........
by NetWallah (Abbot) on Oct 10, 2012 at 06:12 UTC
    Your structure and logic is much more complicated than necessary, but I have preserved it, and made a few corrections. Try this one:
    use strict; use warnings; use Data::Dumper; my %ex = ( 37 => "p" , 41 => "t", 23 => "s" , 52 => "m", 44 => "a" , 65 => "q", 26 => "d" , 88 => "o" , 99 => "g" , 100 => "l" , 101 => "f" , 201 => "i" ); my @buckets = ( [],[],[],[],[],[],[],[],[],[] ); sub perlhash { my $k = shift @_; my $hash = 0; $hash = ($k % 10); return $hash; } while(my ($k , $v) = each(%ex)) { my $hash = perlhash($k); my $ch = $buckets[$hash]; my $entry; # print Dumper $buckets[$hash]; if(scalar @{$ch} == 0){ $entry = {$k => $v}; }else{ $entry = $ch->[0]; $entry->{$k} = $v ; next; } push @$ch , $entry; } print Dumper \@buckets; print "enter a key u want to search"; chomp(my $k = <STDIN>); my $h = perlhash($k); print "The Key in Slot $h is " . join (",",keys (%{$buckets[$h][0]}) +) . "\n" ;

                 I hope life isn't a big joke, because I don't get it.
                       -SNL

      Thnks 4 ur reply. bt u didn't reply 4 my whole question. as i also asked if i search for 47 . then it is giving me index 7 . and at 7 index 37 is given . so its giving me 37 . bt it should give me that this key is not available. means how colud i compare my whole keys with key 47. so i can say it is not avaialbe

      and one thing more if i searched for 201 then there are two keys there then how it will give 201.

        #!/usr/local/bin/perl use warnings; use strict; use Text::Autoformat 'autoformat'; my $horrid = <<'_INPUT_'; Thnks 4 ur reply. bt u didn't reply 4 my whole question. as i also ask +ed if i search for 47 . then it is giving me index 7 . and at 7 index 37 is gi +ven . so its giving me 37 . bt it should give me that this key is not available +. means how colud i compare my whole keys with key 47. so i can say it is not avaialbe and one thing more if i searched for 201 then there are two keys there then how it will give 201. _INPUT_ for ( $horrid ) { s/\b i \b/I/gxms; s/\b bt \b/but/gxms; s/\b 4 \b/for/gxms; s/\b u \b/you/gxms; s/\b ur \b/your/gxms; s/[ ]([.?!])/$1/gms; } print autoformat( $horrid , { 'squeeze' => 1 , 'justify' => 'left' , 'case' => 'sentence' , 'left' => 0 , 'right' => 78 } ); __END__ Thnks for your reply. But you didn't reply for my whole question. As I + also asked if I search for 47. then it is giving me index 7. and at 7 index + 37 is given. So its giving me 37. but it should give me that this key is not available. Means how colud I compare my whole keys with key 47. so I c +an say it is not avaialbe and one thing more if I searched for 201 then there are two keys there then how it will give 201.
        If you want to fail the search when the item is not found, you need to add the following line before the final "print"
        die "$k was not found (slot $h)" unless grep {$k==$_} keys (%{$buckets +[$h][0]});
        There are actually 3 keys in the "201" slot.
        If you run the code I posted, it will show all three.
        If you wanted to show only the matched key, you can use a grep statement , very similar to the one above.

                     I hope life isn't a big joke, because I don't get it.
                           -SNL

Re: trying to implement hash table. and getting lots of difficulties. plz help me out..........
by kcott (Abbot) on Oct 10, 2012 at 07:25 UTC

    G'day Priti24,

    Perl already provides the functionality you describe. So, unless you have a specific reason for re-inventing the wheel (which may be perfectly valid but isn't addressed in your post), you can use code like this to achieve what you're after.

    #!/usr/bin/env perl use strict; use warnings; my %ex = ( 37 => 'p', 41 => 't', 23 => 's', 52 => 'm', 44 => 'a', 65 => 'q', 26 => 'd', 88 => 'o', 99 => 'g', 100 => 'l', 101 => 'f', 201 => 'i +' ); print 'Enter the key you want to search for: '; my $k = <>; chomp $k; if (exists $ex{$k}) { print "The key '$k' has the value: $ex{$k}\n"; } else { print "The key '$k' doesn't exist.\n"; }

    Here it is in action with the three keys you mention (37, 47 & 101):

    $ pm_hash_search.pl Enter the key you want to search for: 37 The key '37' has the value: p $ pm_hash_search.pl Enter the key you want to search for: 47 The key '47' doesn't exist. $ pm_hash_search.pl Enter the key you want to search for: 101 The key '101' has the value: f

    Here's some of the things you could have done better in the code you provided:

    • Let Perl tell you when you're doing something potentially problematic, or just plain wrong, with strict and warnings. See usage in my code.
    • Declare your variables. my is used most often - see my %ex and my $k in my code. With no declarations, all your variables become global which has all sorts of implications and is basically a headache you don't need to have. (There are other ways to declare variables - see perlsub for details.)
    • You call your subroutine with an argument (perlhash($k)) but don't read that argument in the subroutine code. In this instance, my $k = shift; would have been sufficient; for multiple arguments, use something like my ($arg1, ..., $argN) = @_; - see perlsub for details.
    • It's easy to mistype, misread or miscount the exact number of arrayrefs in @buckets = ( [],[],[],[],[],[],[],[],[],[] );. You can use the x operator to avoid all three types of problems: @buckets = ([]) x 10; - see perlop for details.
    • When you read user input (typed from the keyboard) you'll get all the keystrokes including the final return. Use chomp to remove this (as I did in my code).
    • Your code would be easier to read if it was laid out a little better - perlstyle has some suggestions regarding this.

    -- Ken

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://998135]
Approved by chacham
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2014-09-01 22:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (17 votes), past polls