Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 364
Yvonne Avatar asked May 10 '18 23:05

Yvonne


People also ask

How do you pass an optional parameter?

By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.

How do you pass a function parameter in Perl?

You can pass various arguments to a Perl subroutine like you do in any other programming language and they can be accessed inside the function using the special array @_. Thus the first argument to the function is in [0],thesecondisin_[1], and so on.

How do I pass a variable by reference in Perl?

Passing by reference allows the function to change the original value of a variable. When the values of the elements in the argument arrays @_ are changed, the values of the corresponding arguments will also change. This is what passing parameters by reference does.


1 Answers

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.

like image 191
simbabque Avatar answered Sep 20 '22 04:09

simbabque