Gossamer Forum
Home : General : Perl Programming :

Retrieving Hash Value

Quote Reply
Retrieving Hash Value
Hi,

I need to retrieve value from a hash variable, corresponding to the input. This is how the code goes..

print "Message ID:";

$input = <STDIN>;

for($i=0; $i< $total_msg; $i++){

if ($input == $msg{$i}{msg_id}) {

$msg_body = $msg{$i}{message_body};

last;

}

}

With the above code, instead of printing just one message body corresponding to the input message id, it gives me the body of all the messages stored in hash.

Could anyone please tell me how to fix the following code?

Thank you,

Priya.
Quote Reply
Re: [priyarak] Retrieving Hash Value In reply to
Quote:
instead of printing just one message body

It doesn't print anything Crazy

You also have a "last;" in there which would prevent the loop carrying on if a match was found.

Your data structure looks like a hash of hashrefs which is like:

Code:
%hash = (
this => {
msg_id => 1,
msg_body => 'Hello'
},
that => {
msg_id => 2,
msg_body => 'Hello'
}
);

....so I'm not sure how it can be returning all body data as in order to do that you'd have to loop the hashrefs or append them somehow.

Maybe you should provide some more details to see if it clears things up.
Quote Reply
Re: [priyarak] Retrieving Hash Value In reply to
$msg->{$i}->{Name}

Unsure

Cheers

Andy (mod)
andy@ultranerds.co.uk
Want to give me something back for my help? Please see my Amazon Wish List
GLinks ULTRA Package | GLinks ULTRA Package PRO
Links SQL Plugins | Website Design and SEO | UltraNerds | ULTRAGLobals Plugin | Pre-Made Template Sets | FREE GLinks Plugins!
Quote Reply
Re: [Andy] Retrieving Hash Value In reply to
Thats the same as:

$msg{$i}{msg_body}
Quote Reply
Re: [Jinxed] Retrieving Hash Value In reply to
hi,

thank you for your reply.

the data structure is like this --




%msg = (

$total_msg[0] => {

msg_id = a@ab.com

msg_body = "Howdy!"

},

$total_msg[1] => {

msg_id = b@cd.com

msg_body = "Hello"

}

);




Upon taking a message_id as input, I need to retrieve the corresponding message_body.

Could you tell me how I should do it?

Thanks,

Priya.
Quote Reply
Re: [priyarak] Retrieving Hash Value In reply to
Pretty much like you already have it.

Code:
for (keys %msg) {
if ($input eq $msg{$_}->{msg_id}) {
$body = $msg{$_}->{msg_body};
last;
}
}
Quote Reply
Re: [Jinxed] Retrieving Hash Value In reply to
i doesnt work yet! Unsure
Quote Reply
Re: [priyarak] Retrieving Hash Value In reply to
It does, so either I misunderstood what you need or you are missing something :)
Quote Reply
Re: [Paul] Retrieving Hash Value In reply to
Would using "ARGV" solve the purpose?

Priya
Quote Reply
Re: [priyarak] Retrieving Hash Value In reply to
I don't know, because I'm still not clear on what you are trying to do.