在Perl中多维散列工作? [英] Working with multi dimensional hashes in Perl?

查看:276
本文介绍了在Perl中多维散列工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关推动在Perl多维哈希快速的问题。我有以下变量:

 %的PID哈希#NAME
$ PID = 24633#键的有
$ 00时间:0 #TIME参考
$线#has一行充分的数据

我输入查询$ PID,并从$线$时间英寸如果密钥24633参考元素存在05顺:3,那么它的行添加到05:3和05使用:3作为重点。

{的PID 24633} {05:3}

我试过:

 如果($的PID {$ PID} {$时间}){
     @ {$ {的PID PID $} {$时间}} - > $线;
}

我也试过这样:

 如果($的PID {$ PID} {$时间}){
    推@ {$ {的PID PID $} {$时间}} $行;

但它一直给我一个不是一个散列引用,当它试图做推。有什么建议么?谢谢!

这是我要建哈希:

 我的foreach $键(按键%的PID){
    如果($关键=〜$ MPID){
    推@messages,$线;
    }
}

下面是哈希结构:

  $ VAR1 = {
      '17934'=> [
                   '14:3'
                 ]
      '17955'=> [
                   '13:3'
                 ]
      '24633'=> [
                   05:3'
                 ]
      '6771'=> [
                  04:1
                ]
      '7601'=> [
                  '06:0'
                ]
};


解决方案

%的PID 结构,当你试图访问它初始化为数组的哈希哈希散列

 使用严格的;
使用警告;我的PID%=(
    '17934'=> ['14:3'],
    '17955'=> ['13:3'],
    '24633'=> [05:3'],
    '6771'=> ['04:1'],
    '7601'=> [06:0]
);打印$ {的PID 7601} [0],\\ n; #打印06:0打印$ {的PID 7601} {06:0}; #错误

您得弄清楚为什么你的%的PID 是数组的哈希第一,如果你真的希望它是数组的哈希散列。

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'
                ],
};

解决方案

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.

这篇关于在Perl中多维散列工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆