filter_add#
Install a source filter for the current package. Called from the filter module’s import.
Synopsis#
filter_add($object); # method filter: $object is blessed state
filter_add(sub { ... }); # closure filter: anonymous sub
What you get back#
Nothing. filter_add registers the filter as a side effect; the
compiler now routes every subsequent read through it until the
filter calls filter_del or compilation of the enclosing file
finishes.
The shape of the argument picks the filter style:
A
CODEreference — closure filter. The sub is called for every compiler read; state lives in lexicals captured by the closure.Anything else — method filter. If the argument is a plain scalar or an unblessed
ARRAY/HASHreference,filter_addblesses a reference to it into the caller’s package, so the caller’sfiltermethod receives it as$self. An already-blessed reference is used as-is.
Examples#
A closure filter installed from import:
sub import {
filter_add(sub {
my $status = filter_read();
tr/a-z/A-Z/ if $status > 0;
$status;
});
}
A method filter that carries a substitution count as its state:
sub import {
my $count = 0;
filter_add(\$count); # becomes $self in filter()
}
sub filter {
my ($self) = @_;
my $status = filter_read();
$$self++ if s/Joe/Jim/g && $status > 0;
$status;
}
Edge cases#
filter_addlooks up the caller’s package throughcaller, so it must be called from the filter module’simport(or a sub called directly by it). Invoking it from a deeply nested helper will bless the state object into the wrong package.Source filters only act during compilation. Calling
filter_addat runtime (outside anyuse/BEGINchain) has no effect.Passing neither a blessed reference nor a code reference is legal:
filter_addwraps and blesses the value for you.
Differences from upstream#
Fully compatible with upstream Filter::Util::Call 1.65.
See also#
filter_read— the read primitive every filter body calls.filter_del— stop the filter from inside its own body.Filter::Simple— a higher-level wrapper around this module, preferred for new filters that do not need the fine-grained read control.