Skip to content
Patrick Hochstenbach edited this page May 16, 2014 · 25 revisions

Bind function are a new addition to Catmandu version 0.91 [?]. They are used to provide processing hooks around Fix functions.

As a reminder, Fix functions are used to manipulate data. Perl hashes get in and Perl hashes get out. The 'meow' fix below will add a field to an incoming Perl hash:

package Catmandu::Fix::meow;
use Moo;

sub fix {
    my ($self,$data) = @_;
    $data->{'meow'} = 'Prrr';
    $data;
}

1;

Using the Fix you can do something like:

$ echo "{}" | catmandu convert --fix 'meow();' 
$ { "meow": "Prrr" }

Binds can be used to manipulate Fix functions. A Perl hash, a code reference (representing the Fix function) and a Fix function name get in, a manipulated Perl hash gets out. As an easy example, let's create a 'bark' Bind which barks every time a 'meow' Fix gets executed.

package Catmandu::Fix::Bind::bark;
use Moo;
with 'Catmandu::Fix::Bind';

sub bind {
    my ($self,$data,$coderef,$fix_name) = @_;
    if ($fix_name eq 'meow') {
        warn "woof! woof!";
    }
    # execute the fix
    return $coderef->($data);
}

1;

We can execute this 'bark' Bind by using a new 'do' keyword in the Fix language:

$ echo "{}" | catmandu convert --fix 'do bark(); meow(); end'
woof! woof!
{ "meow": "Prrr" }
$ echo "{}" | catmandu convert --fix 'do bark(); meow(); meow(); meow(); end'
woof! woof!
woof! woof!
woof! woof!
{ "meow": "Prrr" }

You can use Bind to manipulate the data, execute code before or after a Fix function, and are generally used to cope with side effects. Catmandu 0.91 will provide 4 Bind functions as examples.

#####identity The identity Bind doesn't do anything really to manipulate the incomming data or Fix functions. You can use identity binds to group Fix functions for other binds. E.g.:

do
  identity();
  foo();
  bar();
end

has the same effect as:

foo();
bar();
maybe

The maybe Bind can be used around Fix functions that can throw errors. The Bind will catch errors and start ignoring all Fix functions that succeed the Fix which threw the error. E.g.:

do 
   maybe();
   foo();
   aargh_bad_fix(); # throws an error
   bar();
end

has the same effect as:

foo(); 
list

The list Bind can be used to execute Fix functions (or nested Binds) multiple times on every element in a list. E.g.:

add_field(demo.$append.test,1)
add_field(demo.$append.test,2)

do list(path => demo)
add_field(foo,bar)
end

has the same effect as:

add_field(demo.$append.test,1)
add_field(demo.$append.test,2)

add_field(demo.0.foo , bar)
add_field(demo.1.foo , bar)
Clone this wiki locally