使用Tie :: IxHash的perl哈希数组

时间:2012-08-06 15:17:18

标签: arrays perl hash

我正在尝试创建一个哈希数组,每个哈希都是绑定的,有序的IxHash。循环遍历我的初始哈希时,键确实是有序的。但是,只要我将它们推入阵列,排序就会消失。我知道这是我对哈希在数组上推送时发生的事情的了解不足,但是如果有人能够启发我,那将非常感激。

#! /usr/bin/perl -w

use strict;
use Data::Dumper;
use Tie::IxHash;

my @portinfo;

tie (my %portconfig, 'Tie::IxHash',
      'name' => [ 'Name', 'whatever' ],
      'port' => [ 'Port', '12345' ],
      'secure' => [ 'Secure', 'N' ]
      );

print "Dump of hash\n";
print Dumper(%portconfig);

print "\nDump of array\n";
push @portinfo, {%portconfig}; 
print Dumper(@portinfo);

这个的输出: -

Dump of hash
$VAR1 = 'name';
$VAR2 = [
          'Name',
          'whatever'
        ];
$VAR3 = 'port';
$VAR4 = [
          'Port',
          '12345'
        ];
$VAR5 = 'secure';
$VAR6 = [
          'Secure',
          'N'
        ];

Dump of array
$VAR1 = {
          'secure' => [
                        'Secure',
                        'N'
                      ],
          'name' => [
                      'Name',
                      'whatever'
                    ],
          'port' => [
                      'Port',
                      '12345'
                    ]
        };

1 个答案:

答案 0 :(得分:6)

您的代码:

push @portinfo, {%portconfig}; 
print Dumper(@portinfo);

获取绑定的散列%portconfig并将其内容放入新的匿名散列中,然后将其推送到@portinfo。因此,您的数组中有一个匿名的,无序的哈希。

你可能想做的是

push @portinfo, \%portconfig; 
print Dumper(@portinfo);

这会将引用推送到%portconfig @portinfo,从而保留您所需的订单。

因此:

#! /usr/bin/perl -w

use strict;
use Data::Dumper;
use Tie::IxHash;

my @portinfo;

tie (my %portconfig, 'Tie::IxHash',
      'name' => [ 'Name', 'whatever' ],
      'port' => [ 'Port', '12345' ],
      'secure' => [ 'Secure', 'N' ]
      );

print "Dump of hash\n";
print Dumper(%portconfig);

print "\nDump of array\n";
push @portinfo, \%portconfig; 
print Dumper(@portinfo);

给出

C:\demos>perl demo.pl
Dump of hash
$VAR1 = 'name';
$VAR2 = [
          'Name',
          'whatever'
        ];
$VAR3 = 'port';
$VAR4 = [
          'Port',
          '12345'
        ];
$VAR5 = 'secure';
$VAR6 = [
          'Secure',
          'N'
        ];

Dump of array
$VAR1 = {
          'name' => [
                      'Name',
                      'whatever'
                    ],
          'port' => [
                      'Port',
                      '12345'
                    ],
          'secure' => [
                        'Secure',
                        'N'
                      ]
        };