Sub::Parameters - enhanced parmeter handling


 use Sub::Parameters;

 sub foo : WantParam {
     my $foo : Parameter;
     my $bar : Parameter(rw);

     $bar = 'foo';
     print "the foo parameter was '$foo'\n";

 my $foo = 'bar';
 print "foo is '$foo';     # prints bar
 foo(1, $foo);
 print "foo is now '$foo'; # prints foo


Sub::Parameters provides a syntactic sugar for parameter parsing.

It's primary interface is via attributes, you first apply notation to the subroutine that you wish it to use extended parameter passing, and of what style with the WantParams attribute. You can then annotate which lexicals within that subroutine are to be used to receive parameters.

There are currently two styles of argument parsing supported positional and named.

Positional parameters

With the positional scheme parameters are assigned from @_ in the same order as in the program text, as we see in the following example.

 sub example : WantParams(positional) {
     my $baz : Parameter;
     my $bar : Parameter;

     print $bar; # prints 'first value'
     print $baz; # prints 'second value'

 example( 'first value', 'second value' );

Positional is the default scheme.

Named parameters

With the named scheme parameters are assigned from @_ as though it was an arguments hash, with the variable names as keys.

 sub demonstration : WantParams(named) {
     my $bar : Parameter;
     my $baz : Parameter;

     print $bar; # prints 'bar value'
     print $baz; # prints 'baz value'

 demonstration( foo => 'foo value',
                baz => 'baz value',
                bar => 'bar value'  );

Readwrite parameters

Both positional and named parameters may be marked as readwrite (rw in the code.) A readwrite parameter is passed by reference so modifying the value within the subroutine modifies the original.

 sub specimen : WantParams {
     my $foo : Parameter(rw);

     print $foo; # prints 'foo value'
     $foo = "new value";

 my $variable = "foo value";
 specimen( $variable );
 print $variable; # prints 'new value'

Alternate parameter syntax

For versions of perl older than 5.7.3 or 5.8.0 lexical attributes have an implementation flaw. In this case there is an alternative syntax for identifying parameters:

 use Sub::Parameters 'Param';
 sub illustration: WantParams {
     Param( my $foo );
     Param( my $bar = 'rw' );


Think about positional @foo:Parameter slurp rather than @foo = [] semantics
think about methods


Attribute::Handlers, PadWalker, Hook::LexWrap, Devel::LexAlias


Richard Clamp <>


Copyright (c) 2002, Richard Clamp. All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.