File: parse_text.pm

package info (click to toggle)
libcatmandu-perl 1.2024-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,552 kB
  • sloc: perl: 17,037; makefile: 24; sh: 1
file content (77 lines) | stat: -rw-r--r-- 1,567 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package Catmandu::Fix::parse_text;

use Catmandu::Sane;

our $VERSION = '1.2024';

use Moo;
use Catmandu::Util::Path  qw(as_path);
use Catmandu::Util::Regex qw(as_regex);
use namespace::clean;
use Catmandu::Fix::Has;

has path    => (fix_arg => 1);
has pattern => (fix_arg => 1);

with 'Catmandu::Fix::Builder';

sub _build_fixer {
    my ($self) = @_;
    my $regex = as_regex($self->pattern);
    as_path($self->path)->updater(
        if_string => sub {
            my $val = $_[0];
            if ($val =~ m/$regex/) {
                if (@+ < 2) {    # no capturing groups
                    return undef, 1, 0;
                }
                elsif (%+) {     # named capturing groups
                    return +{%+};
                }
                else {           # numbered capturing groups
                    no strict 'refs';
                    return [map {${$_}} 1 .. (@+ - 1)];
                }
            }
            return undef, 1, 0;
        }
    );
}

1;

__END__

=pod

=head1 NAME

Catmandu::Fix::parse_text - parses a text into an array or hash of values

=head1 SYNOPSIS

    # date: "2015-03-07"
    parse_text(date, '(\d\d\d\d)-(\d\d)-(\d\d)')
    # date: 
    #    - 2015
    #    - 03
    #    - 07 

    # date: "2015-03-07"
    parse_text(date, '(?<year>\d\d\d\d)-(?<month>\d\d)-(?<day>\d\d)')
    # date:
    #   year: "2015"
    #   month: "03" 
    #   day: "07"

    # date: "abcd"
    parse_text(date, '(\d\d\d\d)-(\d\d)-(\d\d)')
    # date: "abcd"

=head1 SEE ALSO

L<Catmandu::Fix>

L<Catmandu::Importer::Text>

=cut