How do I change this to “idiomatic” Perl?

前端 未结 6 2256
名媛妹妹
名媛妹妹 2021-02-09 03:46

I am beginning to delve deeper into Perl, but am having trouble writing \"Perl-ly\" code instead of writing C in Perl. How can I change the following code to use more Perl idiom

6条回答
  •  南方客
    南方客 (楼主)
    2021-02-09 04:11

    You're getting several suggestions regarding syntax, but I would also suggest a more modular approach, if for no other reason that code readability. It's much easier to come up to speed on code if you can perceive the big picture before worrying about low-level details.

    Your primary method might look like this.

    sub create_matrix {
        my $self = shift;
        $self->create_2d_array_of_scores;
        $self->fill_out_first_row;
        $self->fill_out_other_rows;
    }
    

    And you would also have several smaller methods like this:

    n_of_rows
    n_of_cols
    create_2d_array_of_scores
    fill_out_first_row
    fill_out_other_rows
    

    And you might take it even further by defining even smaller methods -- getters, setters, and so forth. At that point, your middle-level methods like create_2d_array_of_scores would not directly touch the underlying data structure at all.

    sub matrix      { shift->{score_matrix} }
    sub gap_cost    { shift->{gap_cost}     }
    
    sub set_matrix_value {
        my ($self, $r, $c, $val) = @_;
        $self->matrix->[$r][$c] = $val;
    }
    
    # Etc.
    

提交回复
热议问题