如何在Perl中传递可选参数?(适合初学者)

Yvo*_*nne 6 perl subroutine

我已经阅读了http://www.perl101.org/subroutines.html但我只是不了解可选参数.

我想在PDF :: API2中调用以下子.该文件称"-indent"是一种选择.我如何为缩进20传递参数?

这就是我现在所经过的:

$txt->section($str, $contentwidth,$heightmax);
Run Code Online (Sandbox Code Playgroud)

这是子

sub section {
    my ($self,$text,$width,$height,%opts)=@_;
    my $overflow = '';

    foreach my $para (split(/\n/,$text)) {
        if(length($overflow) > 0) {
            $overflow .= "\n" . $para;
            next;
        }
        ($para,$height) = $self->paragraph($para,$width,$height,%opts);
        $overflow .= $para if (length($para) > 0);
    }
    if (wantarray) {
        return ($overflow,$height);
    }
    return $overflow;
}
Run Code Online (Sandbox Code Playgroud)

sim*_*que 8

my ($self, $text, $width, $height, %opts) = @_;
Run Code Online (Sandbox Code Playgroud)

%opts给它了.您需要传递键和值对的列表.它不是一个参考,只是可选的附加值.

$self获取您插入被Perl.然后你已经获得了已经通过的三个必需参数.在那之后,它的选择.

$obj->section( $text, $width, $height, -indent => 1 );
Run Code Online (Sandbox Code Playgroud)

分配这些选项的方式%opts将在高度之后将所有剩余的参数粘贴到该哈希中,并将在$self->paragraph稍后传递.

只要确保它总是成对的值.