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

1

5

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;
}
Dandelion answered 10/5, 2018 at 23:1 Comment(0)
U
8
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.

Ursula answered 10/5, 2018 at 23:46 Comment(4)
Thanks for the edit @Borodin. I wrote this at night from my phone.Ursula
@vanHoesel your edit was actually not bad. I'll take up some of it. Thanks.Ursula
Great, thanks! I didn't realise the hyphen was supposed to be in there as well.Dandelion
@Dandelion that's a valuable lesson learned here. In programming every character matters. There is no approximation. Things are either correct or they are not. Most of the time it's a semicolon that is missing, but this kind of thing here is easy harder to track down, especially when your language is as forgiving as Perl is. :-)Ursula

© 2022 - 2024 — McMap. All rights reserved.