user5485904
user5485904

Reputation: 21

Perl multiple optional parameters

I have a perl submodule which has 3 parameters: $text,$color,$font
Out of these paramters, $color and $font are optional.

If I need to pass only $font without $color, how can it be done as perl will assign the font string to $color when shift is used.

Upvotes: 0

Views: 213

Answers (2)

Seekheart
Seekheart

Reputation: 1173

you can use the Getopt module.

use Getopt::Long;

#make options
my $text;
my $color;
my $font;

GetOptions('-text=s' => $text, '-color=s' => $color, '-font=s' => $font,);

unless ($text){
     die "No text arg provided";
}

#do something

Upvotes: 0

Mark Reed
Mark Reed

Reputation: 95242

The usual solution for multiple optional parameters is to take a hash.

sub myfunction {
  my %options = @_;
  my ($text, $color, $font) = @options{qw(text color font)};
  ...
}

then you call it like this:

myfunction( font => 'font goes here', text => "Here's the text") # no color

Upvotes: 7

Related Questions