NAME

Getopt::EX::Func - Function call interface

SYNOPSIS

use Getopt::EX::Func qw(parse_func);

my $func = parse_func("func_name(key=value,flag)");

$func->call;

DESCRIPTION

This module provides a way to create function call objects used in the Getopt::EX module set.

For example, suppose your script has a --begin option that specifies a function to call at the beginning of execution. You can implement it like this:

use Getopt::EX::Func qw(parse_func);

GetOptions("begin:s" => \$opt_begin);

my $func = parse_func($opt_begin);

$func->call;

The user can then invoke the script as:

% example -Mfoo --begin 'repeat(debug,msg=hello,count=2)'

The function repeat should be declared in module foo or in a startup rc file such as ~/.examplerc. It can be implemented like this:

our @EXPORT = qw(repeat);
sub repeat {
    my %opt = @_;
    print Dumper \%opt if $opt{debug};
    say $opt{msg} for 1 .. $opt{count};
}

FUNCTION SPEC

The parse_func function accepts the following string formats.

A function name can optionally be prefixed with &, and parameters can be specified in two equivalent forms using parentheses or =:

func(key=value,key2=value2)
func=key=value,key2=value2
&func(key=value)

So the following two commands are equivalent:

% example --begin 'repeat(debug,msg=hello,count=2)'
% example --begin 'repeat=debug,msg=hello,count=2'

Both will call the function as:

repeat( debug => 1, msg => 'hello', count => '2' );

Arguments are passed as key => value pairs. Parameters without a value (debug in this example) are assigned the value 1. Key names may contain word characters (alphanumeric and underscore), hyphens, and dots.

Commas normally separate parameters. If a value needs to contain commas, there are two ways to handle this:

Parentheses

Commas inside parentheses are preserved:

func(pattern=(a,b,c),debug)

This calls:

func( pattern => '(a,b,c)', debug => 1 );

Note that the parentheses are included in the value.

Tilde

Use ~ instead of = to capture the entire remaining string as the value:

func(debug,pattern~a,b,c)

This calls:

func( debug => 1, pattern => 'a,b,c' );

Since ~ consumes the rest of the string, no parameters can follow it.

An anonymous subroutine can also be specified inline:

% example --begin 'sub{ say "wahoo!!" }'

The function is evaluated under use v5.14, so features like say are available.