簡體   English   中英

如何在Perl的哈希中存儲2d數組?

[英]How do I store a 2d array in a hash in Perl?

我在perl中的對象中苦苦掙扎,並嘗試創建2d數組並將其存儲在對象的哈希字段中。 我知道要創建一個2d數組,我需要一個數組引用數組,但是當我嘗試執行此操作時,我會收到以下錯誤消息: Type of arg 1 to push must be array (not hash element)構造函數工作正常,並且set_seqs工作正常,但我的create_matrix子程序拋出這些錯誤。

這是我在做什么:

sub new {
    my ($class) = @_;
    my $self = {};
    $self->{seq1} = undef;
    $self->{seq2} = undef;
    $self->{matrix} = ();
    bless($self, $class);
    return $self;
}
sub set_seqs {
    my $self = shift;
    $self->{seq1} = shift;
    $self->{seq2} = shift;
    print $self->{seq1};
}

sub create_matrix {
    my $self = shift;
    $self->set_seqs(shift, shift);
    #create the 2d array of scores
    #to create a matrix:
    #create a 2d array of length [lengthofseq1][lengthofseq2]
    for (my $i = 0; $i < length($self->{seq1}) - 1; $i++) {
        #push a new array reference onto the matrix
        #this line generates the error
        push(@$self->{matrix}, []);
    }
}

任何我做錯事的想法嗎?

取消引用$ self時,會丟失一組額外的花括號。 嘗試push @{$self->{matrix}}, []

如有疑問(如果不確定是否要在復雜的數據結構中引用正確的值),請添加更多括號。 :)參見perldoc perlreftut

Perl是一種非常有表現力的語言。 您可以使用以下語句完成所有操作。

$self->{matrix} = [ map { [ (0) x $seq2 ] } 1..$seq1 ];

這是高爾夫嗎? 也許可以,但是它避免了挑剔的原型push 我將下面的語句分解為:

$self->{matrix} = [     # we want an array reference
    map {               # create a derivative list from the list you will pass it
        [ (0) x $seq2 ] # another array reference, using the *repeat* operator 
                        # in it's list form, thus creating a list of 0's as 
                        # long as the value given by $seq2, to fill out the  
                        # reference's values.
   } 
   1..$seq1             # we're not using the indexes as anything more than  
                        # control, so, use them base-1.
];                       # a completed array of arrays.

我有一個標准的子程序來制作表格:

sub make_matrix { 
    my ( $dim1, $dim2 ) = @_;
    my @table = map { [ ( 0 ) x $dim2 ] } 1..$dim1;
    return wantarray? @table : \@table;
}

這是一個更通用的數組數組函數:

sub multidimensional_array { 
    my $dim = shift;
    return [ ( 0 ) x $dim ] unless @_; # edge case

    my @table = map { scalar multidimensional_array( @_ ) } 1..$dim;
    return wantarray ? @table : \@table;
}
sub create_matrix {
    my($self,$seq1,$seq2) = @_;
    $self->set_seqs($seq2, $seq2);

    #create the 2d array of scores
    #to create a matrix:
    #create a 2d array of length [$seq1][$seq2]
    for( 1..$seq1 ){
        push @{$self->{matrix}}, [ (undef) x $seq2 ];
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM