NAME
Tie::Sub - Tying subroutine to a hash
SYNOPSIS
Sample 1: like function
use strict;
use warnings;
use Tie::Sub;
# one step for tie and configure
tie my %sub, 'Tie::Sub', sub{sprintf '%04d', shift};
print "See $sub{4} digits.";
# result is:
# See 0004 digits.
Sample 2: like subroutine
use strict;
use warnings;
use Tie::Sub;
Save the object $sub if you like to use it later.
my $sub = tie my %sub, 'Tie::Sub';
Here you can see the other way to configure after tie. Configuration can be repeated. $sub is the same like tied(%sub) but to save the objekt is much easier.
$sub->Config( sub{ [ map sprintf("%04d\n", $_), @_ ] } );
print @{ $sub{[0..2]} }; # Hash key and return value are both array references.
# results are:
# 0000
# 0001
# 0002
Read configuration
my $config = tied(%sub)->Config;
Write configuration
my $config = tied(%sub)->Config( sub{yourcode} );
DESCRIPTION
Subroutines don't have interpreted into strings. The module ties a subroutine to a hash. The subroutine is executed at fetch hash. At long last this is the same, only the notation is shorter.
Alternative to "...@{[sub('abc')]}..."
or '...'.sub('abc').'...'
write "...$sub{abc}..."
.
Think about:
use Tie::Sub;
HTML::Entities;
tie my %encode_entities, 'Tie::Sub', sub{encode_entities shift);
print <<EOT;
<html>
...
$encode{'<abc>'}
...
EOT
Sometimes the subroutine expects more than 1 parameter. Then submit a reference on an array as "
hash key"
. The tied sub will get the parameters as scalar or array.
Use any reference to give back more then 1 return value. The caller get back this reference. There is no way to return a list.
METHODS
TIEHASH
use Tie::Sub;
my $object = tie my %sub, 'Tie::Sub', sub{yourcode};
"
TIEHASH"
ties your hash and set options defaults.
Config
"
Config"
stores your own subroutine
You can get back the former code reference or use the method Config in void context. When you configure the first subroutine, the method will give back undef.
$coderef = tied(%sub)->Config(sub {yourcode});
The method calls croak if you have a parameter and this parameter is not a reference of "
CODE"
.
FETCH
Give your parameter as key of your tied hash. This key can be a string or an array reference when you have more then one. "
FETCH"
will run your tied sub and give back the returns of your sub. Think about, return value can't be a list, but reference of such things.
print $sub{param};
DESTROY
Free encapsulated object data.
SEE ALSO
http://perl.plover.com/Identity/
http://perl.plover.com/Interpolation/
Interpolation # contains much things
Tie::Function # maybe there is a problem near $;
in your Arguments
AUTHOR
Steffen Winkler, <cpan@steffen-winkler.de>;
COPYRIGHT AND LICENSE
Copyright (C) 2005 by Steffen Winkler
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.6.1 or, at your option, any later version of Perl 5 you may have available.