从哈希结构的键构建数组

时间:2012-01-01 20:08:56

标签: perl

我有以下子程序OutputingReorderedVectors,其目的是按照一些预先指定的要求输出向量。但是,代码只输出空白文件。

我认为问题应该来自以下代码段,其中涉及从chainRollupDoc的二级哈希重新排序密钥

  my @rollupArray = sort keys %chainRollupDoc;
  my @reorderedSS = ();
  foreach my $i(0 .. $#rollupArray)
    {
        foreach my $cui (sort keys %{$chainRollupDoc->{$rollupArray[$i]}})
          {
            push @reorderedSS, $cui;
          }
    } 

整个子程序如下

#####################################
 sub OutputingReorderedVectors
#####################################
{
  my $centroids = shift;
  my $fileName = shift;
  my $chainRollupDoc = shift;   
  my @rollupArray = sort keys %chainRollupDoc;
  my @reorderedSS = ();
  foreach my $i(0 .. $#rollupArray)
  {
    foreach my $cui (sort keys %{$chainRollupDoc->{$rollupArray[$i]}})
    {
      push @reorderedSS, $cui;
    }
  } 

  my %attributes = ();
  foreach my $category (keys %$centroids)
  {
    foreach my $cui (keys %{$centroids->{$category}})
    {
      $features{$cui} = 1;
    }
  }
  my @fullSpace = sort keys %attributes;
  open(OUTPUT, "> $fileName");

  foreach my $i(0 .. $#reorderedSS)
  {
    printf OUTPUT "\t%s", $reorderedSS[$i];
  }
  print OUTPUT "\n";
  foreach my $i (0 .. $#fullSpace)
  {
    printf OUTPUT "%s", $fullSpace[$i];
    foreach  my $j (0 .. $#reorderedSS)
    {
      printf OUTPUT "\t%f", $centroids->{$reorderedSS[$j]}->{$fullSpace[$i]};
    }
    print OUTPUT "\n";
  }
  close OUTPUT;
}

2 个答案:

答案 0 :(得分:3)

我没有看到%chainRollupDoc被声明的位置,这让我想知道你是否将哈希引用与实际哈希混合。看起来这个函数是用hashref作为第三个参数调用的,因为你说:

my $chainRollupDoc = shift;

但下一行会使用名为%chainRollupDoc哈希。也许你的意思是这个?

my @rollupArray = sort keys %$chainRollupDoc;

(注意美元符号添加到deref hashref)。

答案 1 :(得分:0)

假设你有:

$features{$cui} = 1;

你的意思是:

$attributes{$cui} = 1;

这是您的代码的简化版本:

use warnings; use strict;
use List::MoreUtils qw'uniq';
use autodie;

sub OutputingReorderedVectors{
  my($centroids,$fileName,$chainRollupDoc) = @_;

  my @reorderedSS;
  for my $i( sort keys %$chainRollupDoc ){
    push @reorderedSS, sort keys %{$chainRollupDoc->{$i}}
  }
  # NOTE: @reorderedSS is NOT sorted, only parts of it are.

  my @fullSpace;
  for my $category (values %$centroids){
    push @fullSpace, keys %$category
  }
  @fullSpace = sort uniq @fullSpace;

  open my $output, '>', $fileName;

  print {$output} join( "\t", '', @reorderedSS ), "\n";

  for my $i (@fullSpace){
    print {$output} $i;
    for my $j (@reorderedSS){
      # could possibly be replaced with a simple print statement
      printf {$output} "\t%f", $centroids->{$j}->{$i};
    }
    print {$output} "\n";
  }
  close $output;
}

如果您向我们提供了数据示例以及该数据的预期输出,我们可以为您提供进一步的帮助。

我想指出您正在使用Perl as if it were C进行编程。