Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: can i concatenate various value to form a unique key

by Marshall (Canon)
on Jul 03, 2009 at 09:26 UTC ( [id://776996]=note: print w/replies, xml ) Need Help??


in reply to can i concatenate various value to form a unique key

It is completely fine to make a hash key from other strings. like:
#!/usr/bin/perl -w use strict; my %hash; $hash{'my_mother=Nice,my_brother=Great;3;45;987;'}='True'; foreach my $key (keys %hash) { print "$key VALUE =$hash{$key}\n"; } __END__ prints: my_mother=Nice,my_brother=Great;3;45;987; VALUE =True
Update:
I would argue that this is not the best way:
my $key = join ("",$value1,$value2,$value3,$value4,$value5);
consider:
my $key ="$value1$value2$value3$value4$value5";
if say $value3 doesn't exist, then,
$key = "$value1$value2$value4$value5";
Oooops!...maybe a problem!!!

$hash{"$value1;$value2;$value3;$value4;$value5"} = 123;
is "better" (provided that ";" doesn't occur in the $values).
The reason for the ";" is so that there will always be a unique value even if one of the $value vars is ""!.

Replies are listed 'Best First'.
Re^2: can i concatenate various value to form a unique key
by Anonymous Monk on Jul 03, 2009 at 10:19 UTC
    hoo so is it possible to have mutiple values as key whose combination will be unique? and I dont have to download any CPAN modules for the same also?
      The short answer is yes. A hash key can be any string as long as that string is unique. The "classic example" is printing a file and omitting duplicate lines that have been seen before....
      #!usr/bin/perl -w use strict; my %seen; while (<DATA>) { print unless $seen{$_}++; } #Prints: #1 2 this is a line with 1 and 2 #3 a line with just 3 #5,6 five before 6 #5,6 five before six (different) #6,5 #blah __DATA__ 1 2 this is a line with 1 and 2 3 a line with just 3 1 2 this is a line with 1 and 2 3 a line with just 3 5,6 five before 6 5,6 five before six (different) 6,5 blah blah
      In general, I would not concatenate keys together. Well, until you have learned multi-dimensional structs, I would say that concatenating 2 things and not more is "ok".

      There are some advanced techniques where say 8 dimensions can be combined into a single hash key, but those situations are seldom and not applicable for normal code (a way to describe state tables and a way to simplify horrifically complex logic statements).

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://776996]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2024-03-28 10:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found