Search code examples
perlsubroutine

How to pass optional parameters in Perl? (For a beginner)


I've read http://www.perl101.org/subroutines.html but I just don't understand optional parameters.

I want to call the following sub in PDF::API2. The doc says "-indent" is an option. How exactly do I pass a parameter for indent of 20?

This is what I'm passing at the moment:

$txt->section($str, $contentwidth,$heightmax);

This is the sub

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;
}

Solution

  • my ($self, $text, $width, $height, %opts) = @_;
    

    The %opts gives it away. You need to pass a list of key and value pairs. It's not a reference though, just additional values that are optional.

    The $self gets inserted by Perl for you. Then you've got the three mandatory parameters that you already pass. After that, it's options.

    $obj->section( $text, $width, $height, -indent => 1 );
    

    The way those options are assigned to %opts will slurp all the remaining arguments after the height into that hash and will be passed through to $self->paragraph later on.

    Just make sure it's always pairs of values.