1

quick question about pushing to a multi-dimensional hash in Perl. I have the following variables:

%pids #name of hash 
$pid = 24633 #key of the has 
$time 00:0 #time reference 
$line #has a line full of data

I am inputing $pid and $time in from $line. If the key 24633 exists along with reference element 05:3, then it add the line to 05:3 and use 05:3 as a key.

pids{24633}{05:3}

I've tried:

if ($pids{$pid}{$time}){
     @{$pids{$pid}{$time}} -> $line;
}

I've also tried this:

if ($pids{$pid}{$time}){
    push @{$pids{$pid}{$time}}, $line;

But it's keep giving me a "Not a HASH reference" when it tries to do the push. Any suggestions? Thanks!

This is how I'm building the hash:

foreach my $key (keys %pids){
    if ($key =~ $mPID){
    push @messages, $line;
    }
}  

Here's the hash structure:

$VAR1 = {   
      '17934' => [
                   '14:3'
                 ],
      '17955' => [
                   '13:3'
                 ],
      '24633' => [
                   '05:3'
                 ],
      '6771' => [
                  '04:1'
                ],
      '7601' => [
                  '06:0'
                ],
};
3
  • You have a hash of arrays, but you try to use it as a hash of hashes. Your code is also not relevant to the question, as it does not show how you build your hash. Commented Apr 13, 2014 at 21:34
  • I have included how I built it, thanks Commented Apr 13, 2014 at 21:40
  • Nope, you haven't. You've included how you use the hash to try to build an array, which would with the current code fill the array with undefined values. (Because you use $key, but store $line.) Commented Apr 13, 2014 at 21:47

1 Answer 1

1

Your %pids structure is initialized as a hash of arrays when you're trying to access it as a hash of hash

use strict;
use warnings;

my %pids = (   
    '17934' => [ '14:3' ],
    '17955' => [ '13:3' ],
    '24633' => [ '05:3' ],
    '6771'  => [ '04:1' ],
    '7601'  => [ '06:0' ],
);

print $pids{7601}[0], "\n";  #  Prints 06:0

print $pids{7601}{"06:0"}; # Error

You'll have to figure out why your %pids is a hash of arrays first if you really want it to be a hash of hashes of arrays.

Sign up to request clarification or add additional context in comments.

3 Comments

why would I use one over the other? forgive me, still learning. And thanks for the link, lots of great info
Why would one use a hash over an array? You'd use an array if you wanted an ordered list of values. You'd use a hash if you wanted key, value pair relationships. Only you know your data and therefore which one is needed.
Thank you. I meant a hash of arrays or a hash of hashes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.