473,699 Members | 2,027 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Searching in Hashes

98 New Member
There is a hash in my program.
The problem is I need to search in the hash, but there are some keys that are identical, but I need to get the associated value of all these keys.

when I do something like

$value = $hash{ "theKey" };

obviously I'm only getting the value associated to the first key called "theKey". How can I get the others? Some sort of loop?

thanks
Feb 25 '08 #1
22 2254
KevinADC
4,059 Recognized Expert Specialist
Hashes can not have identical keys. Each key has to be unique. Are you using a hash of hashes or array of hashes?
Feb 25 '08 #2
Gangreen
98 New Member
Hashes can not have identical keys. Each key has to be unique. Are you using a hash of hashes or array of hashes?
Let me give you some mre info; it's an exercise I'm making.

It's like a webshop which has items, a product code, a price and a quantity.

I read a file, which holds a 'database' of items for sale and it's structured like this:
for every item for sale there is a line in the textfile:

value1|value2|v alue3|value4

value1 is unique for every item. Call it a productcode or id number.
anyway due to search querys I will need to be able to get a product code from a title(which is provided by the query).

so I need a hash which has the names of the objects as keys, and the associated values will be the product codes.

now let's say there is a book and a dvd for sale with the exact same name I need to be able to get both product codes out of my hash.

That's the whole problem.

I have doublechecked my hash, and it has two identical keys after reading the file and creating the hash... I printed them all with a foreach loop.

p.s it's just a simple hash, no complicated things, I'm new^^
Feb 25 '08 #3
KevinADC
4,059 Recognized Expert Specialist
The same hash can not have two identical keys. Try it and see:

Expand|Select|Wrap|Line Numbers
  1. %hash = (
  2.    foo => 1,
  3.    foo => 2,
  4.    foo => 3
  5. );
  6.  
  7. foreach my $key (keys %hash) {
  8.    print "$key = $hash{$key}\n";
  9. }
  10.  
I don't know where you are making an error in thinking that your hash does. Post some code so I can take a look at what you are doing.
Feb 26 '08 #4
Gangreen
98 New Member
Expand|Select|Wrap|Line Numbers
  1. sub loadInventory{
  2.      open (INVENTORY, $inventoryPath);
  3.      $line = <INVENTORY>;
  4.      while ($line){
  5.         @fields = split(/\|/ , $line);
  6.         ...
  7.         %inventoryCodes = ($fields[1],$fields[0],%inventoryCodes);
  8.     ...
  9.         $line = <INVENTORY>;
  10.      }
  11. }
  12.  
the file to be read has got for example these two lines:

DVD-432|Harry Potter and the Prisoner of Azkaban|25.00|5
BOOK-432|Harry Potter and the Prisoner of Azkaban|15.00|7

because of the split: the values are:
$fields[0] | $fields[1] | $fields[2] | $fields[3]

so, because of this line:
%inventoryCodes = ($fields[1],$fields[0],%inventoryCode s);

i guess this hash will get two pairs, both with the value "Harry Potter and the Prisoner of Azkaban", but they won't have thesame product code...or am I mistaken?

Thanks for the help btw
Feb 26 '08 #5
WinblowsME
58 New Member
How about storing and printing the data like the following?

Expand|Select|Wrap|Line Numbers
  1. use warnings;
  2. use strict;
  3. use Cwd;
  4.  
  5. &init;
  6.  
  7. sub init
  8. {
  9.    my %data = ();
  10.    my $directory = &getcwd;
  11.  
  12.    open ( IN, "$directory/Input.txt" );
  13.       my $line = <IN>;
  14.  
  15.       while ( $line = <IN> )
  16.       {
  17.          chomp ( $line );
  18.  
  19.          my ( $type_id, $name, $price, $quantity ) = split ( /\s*\|\s*/, $line );
  20.          my ( $type, $id ) = split ( /-/, $type_id );
  21.  
  22.          $data{$id}{$type}{NAME}     = $name;
  23.          $data{$id}{$type}{PRICE}    = $price;
  24.          $data{$id}{$type}{QUANTITY} = $quantity;
  25.       }
  26.    close ( IN );
  27.  
  28.    foreach my $i ( sort keys %data )
  29.    {
  30.       foreach my $t ( sort keys %{$data{$i}} )
  31.       {
  32.          # if ( $t =~ /DVD/i )
  33.          # if ( $t =~ /book/i )
  34.  
  35.          if ( $data{$i}{$t}{NAME} =~ /Harry Potter/i )
  36.          {
  37.             print "$i -> $t -> $data{$i}{$t}{NAME} -> $data{$i}{$t}{PRICE} -> $data{$i}{$t}{QUANTITY}\n";
  38.          }
  39.       }
  40.    }
  41. }
Feb 26 '08 #6
KevinADC
4,059 Recognized Expert Specialist
Expand|Select|Wrap|Line Numbers
  1. guess this hash will get two pairs, both with the value "Harry Potter and the Prisoner of Azkaban", but they won't have thesame product code...or am I mistaken?
"Harry Potter and the Prisoner of Azkaban" is a value, not a key. The key is the product ID. Your code could be written much better.
Feb 26 '08 #7
Gangreen
98 New Member
@WinblowsME: Thanks, but I'm affraid that is not allowed due to other restrictions..

@KevinADC: I'm aware my code isn't good ^^ I'm only into perl a couple days now,

anyway...If Harry Potter and the Prisoner of Azkaban is a value, howcome when I do:

$productCode = $inventoryCodes { Harry Potter and the Prisoner of Azkaban }

the $productCode variable is correct? but ofcourse only the DVD-code, and not both (DVD and BOOK)...I'm confused now ^^
Feb 26 '08 #8
KevinADC
4,059 Recognized Expert Specialist
@KevinADC: I'm aware my code isn't good ^^ I'm only into perl a couple days now,

anyway...If Harry Potter and the Prisoner of Azkaban is a value, howcome when I do:

$productCode = $inventoryCodes { Harry Potter and the Prisoner of Azkaban }

the $productCode variable is correct? but ofcourse only the DVD-code, and not both (DVD and BOOK)...I'm confused now ^^

My mistake, I misread the code:

%inventoryCodes = ($fields[1],$fields[0],%inventoryCode s);

you reversed fields [1] and [0] making field [1] the key and field [0] the value. The fact remains, hashes can not have two identical keys, there is no reason to continue discussing that part of the question. When you build up your hash from the file the last value that was read in from the file that is associated with the key will be stored in the hash. If you need a hash key to have multiple values you have to use more complex data structures, like a hash of arrays or whatever is appropriate.
Feb 26 '08 #9
Gangreen
98 New Member
I believe you about the unique key part.

Ii'm trying to figure out how I'm gonna bypass that problem. probably by working with arrays, which is easy, instead of hashes, but that will be slow with big files..

Do you know any way of creating a hash system in which I can store the names: like "Harry Potter..." and the productcode of the object. With the knowledge that there will be items with identical names but different productcodes AND that I need to be able to find the productcodes of all items mathing a specified name? (because I need to implement a "search" option based on product names)
Feb 26 '08 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

0
1544
by: Carl S. in 't Veld | last post by:
I am trying to generate tiger tree hashes the same way as directconnect does, but I am failing. I checked the output from php with the reference vectors from http://www.cs.technion.ac.il/~biham/Reports/Tiger/test-vectors-nessie-format.dat and they appear to be different! echo bin2hex(mhash(MHASH_TIGER, 'abc'))."<br/>\n"; outputs f258c1e88414ab2a527ab541ffc5b8bf935f7b951c132951
2
1503
by: Michael McGarry | last post by:
Hi, Are there hashes in Python? Michael
8
2744
by: Ben Holness | last post by:
Hi All, I want to create a hash array, based on values in a database. Basically, I want a hash array for each database key and I want to use a sub to get the hash array, but I am having a great deal of difficulty!! I have written an example script, taking out the DB side of things, to explain what I want to do and how I want to do it. I am obviously doing something wrong, but I don't know what :)
2
4010
by: Jeff Thies | last post by:
I need to check if two hashes are identical. My thoughts are something like this: function compareHash(hash1,hash2){ if(hash1.length != hash2.length){return false} for(var key in hash1){ if(hash1 != hash2) return false;
6
5491
by: Jonathan | last post by:
I am hoping that someone more experienced than myself can point me towards what might be the fastest data lookup method to use for storing ip addresses. My situation is that I will need to maintain a list of perhaps 50 ip addresses to be used in a packet sniffing application. For each packet that goes through the application (which will be monitoring all traffic through a switch), I need to see if an entry for the source ip of that packet...
2
2851
by: MartyNg | last post by:
I am running a system that has both Classic ASP applications and a smattering of ASP.NET applications. We want to store passwords on a SQL Server table as their MD5 hashes. What is the safest way to get this hash value, and be able to verify it against user logins in both Classic ASP and ASP.NET? We have been working with the system.security.cryptopgraphy MD5 functions in .NET, and the functions here for Classic ASP...
0
1323
by: HalfCoded | last post by:
hi everyone, I am kind of stuck and therefore would really appreciate some clues: I actually have to run a script which has to compare two elements from two different files which are a blast file and a cdf file I need also to keep the data structure For this I chose the following strategy: -dumping the files into two arrays -doing a pattern matching between the two files.
1
3847
by: pavanponnapalli | last post by:
hi , I have come across a code as below in the perldoc: %hash = map { get_a_key_for($_) => $_ } @array; Could anybody tell me the meaning of the above line? please explain map function with reference to hashes. I have understood the meaning of map in general and have worked with an example. But i could not understand the meaning of the same with respect to hashes. So please help me. Thanks & Regards, pavan.
10
6550
by: aurekha | last post by:
Hi I have hashes with arrays to its keys like, %h1 = ('a'=>, 'b'=>, 'c'=> ); %h2 = ('a'=>, 'b'=>); then, how can i compare the 2 hashes(based on values. not keys) and get distinct values ?
6
9607
KevinADC
by: KevinADC | last post by:
This snippet of code provides several examples of programming techniques that can be applied to most programs. using hashes to create unique results static variable recursive function serialization The code itself generates a list of strings comprised of random numbers. No number will be repeated within a string, and no string will be repeated within the list of strings. Following the code is a brief discussion of how the above...
0
8697
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8621
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9184
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8891
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7759
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5878
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4380
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4634
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3061
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.