NAME

Tie::Sub - Tying subroutine to a hash

SYNOPSIS

Sample 1: like function

use strict;
use warnings;

use Tie::Sub;
tie my %sub, 'Tie::Sub', sub{sprintf '%04d', shift};

print "See $sub{4} digits.";
# result:
# See 0004 digits.

Sample 2: like subroutine

use strict;
use warnings;

use Tie::Sub;
my %sub, 'Tie::Sub';
# the other way to config later
tied(%sub}->Config( sub{ [ map sprintf("%04d\n", $_), @_ ] } );

print @{ $sub{[0..2]} };
# result:
# 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;
tie my %sub, 'Tie::Sub', sub{yourcode};

"TIEHASH" ties your hash and set options defaults.

Config

"Config" stores your own subroutine.

tied(%sub)->Config(sub {yourcode});

The method calls croak, if the key is not a reference of "CODE".

"Config" gives a code reference.

FETCH

Give your parameter as key of your hash. "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

Tie::Hash

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

Tie::LazyFunction

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.