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; }
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With