Fix packages

Patrick Hochstenbach edited this page Apr 16, 2016 · 9 revisions

Create a simple Fix

The easiest way to create a new 'Fix' is by creating a Perl package in the Catmandu::Fix namespace that has a 'fix' instance method. For example:

package Catmandu::Fix::foo;

use Moo;

sub fix {
    my ($self, $data) = @_;

    # modify your data here, for instance...
    $data->{foo} = 'bar';

    $data;
}

1;

When this code is available in your perl library path as Catmandu/Fix/foo.pm it can be used as fix function foo(). To try out save the file as lib/Catmandu/Fix/foo.pm in your local directory and execute:

$ echo '{}' | catmandu -I lib convert JSON --fix "foo()"
{"foo":"bar"}

Fix creation with helper packages

The following instruction is incomplete, see POD of Catmandu::Fix

If you want pass arguments to your fix, you can make use of Moo and Catmandu::Fix::Has to read in required and optional parameters.

package Catmandu::Fix::foo;

use Moo;

has greeting => (fix_arg => 1);  # required first argument
has message  => (fix_arg => 1);  # required second argument
has eol      => (fix_opt => 1, default => sub { '!' });  # optional argument , default '!'

sub fix {
    my ($self,$data) = @_;

    $self->log->debug($self->greeting . ", " . $self->message .  $self->eol. "\n";

    # Fix your data here...

    $data;
}

1;

Now you can write log messages in your Fixes:

$ echo '{}' | catmandu convert --fix 'foo(Hello,World)'
Hello, World!
{}
$ echo '{}' | catmandu convert --fix 'foo(Hello,World, eol: ?)'
Hello, World?
{}

See also Catmandu::Fix::SimpleGetValue.

Extended introduction

For an extended introduction into creating Fix packages read the two blog posts at:

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.