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
named
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.
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' );
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.
rw
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'
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' ); ... }
Attribute::Handlers, PadWalker, Hook::LexWrap, Devel::LexAlias
Attribute::Handlers
PadWalker
Hook::LexWrap
Devel::LexAlias
Richard Clamp <richardc@unixbeard.net>
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.
To install Sub::Parameters, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Sub::Parameters
CPAN shell
perl -MCPAN -e shell install Sub::Parameters
For more information on module installation, please visit the detailed CPAN module installation guide.