package WebPAC::Normalize;
+use Exporter 'import';
+our @EXPORT = qw/
+ _set_ds _set_lookup
+ _set_load_row
+ _get_ds _clean_ds
+ _debug
+ _pack_subfields_hash
+
+ to
+ search_display search display sorted
+
+ rec1 rec2 rec
+ frec frec_eq frec_ne
+ regex prefix suffix surround
+ first lookup join_with
+ save_into_lookup
+
+ split_rec_on
+
+ get set
+ count
+
+/;
use warnings;
use strict;
-use blib;
-use WebPAC::Common;
-use base 'WebPAC::Common';
-use Data::Dumper;
-
-=head1 NAME
-WebPAC::Normalize - data mungling for normalisation
+#use base qw/WebPAC::Common/;
+use Data::Dump qw/dump/;
+use Carp qw/confess/;
-=head1 VERSION
+# debugging warn(s)
+my $debug = 0;
+_debug( $debug );
-Version 0.09
+# FIXME
+use WebPAC::Normalize::ISBN;
+push @EXPORT, ( 'isbn_10', 'isbn_13' );
-=cut
+use WebPAC::Normalize::MARC;
+push @EXPORT, ( qw/
+ marc marc_indicators marc_repeatable_subfield
+ marc_compose marc_leader marc_fixed
+ marc_duplicate marc_remove marc_count
+ marc_original_order
+ marc_template
+/);
-our $VERSION = '0.09';
+=head1 NAME
-=head1 SYNOPSIS
+WebPAC::Normalize - describe normalisaton rules using sets
-This package contains code that mungle data to produce normalized format.
+=cut
-It contains several assumptions:
+our $VERSION = '0.36';
-=over
+=head1 SYNOPSIS
-=item *
+This module uses C<conf/normalize/*.pl> files to perform normalisation
+from input records using perl functions which are specialized for set
+processing.
-format of fields is defined using C<v123^a> notation for repeatable fields
-or C<s123^a> for single (or first) value, where C<123> is field number and
-C<a> is subfield.
+Sets are implemented as arrays, and normalisation file is valid perl, which
+means that you check it's validity before running WebPAC using
+C<perl -c normalize.pl>.
-=item *
+Normalisation can generate multiple output normalized data. For now, supported output
+types (on the left side of definition) are: C<search_display>, C<display>, C<search> and
+C<marc>.
-source data records (C<$rec>) have unique identifiers in field C<000>
+=head1 FUNCTIONS
-=item *
+Functions which start with C<_> are private and used by WebPAC internally.
+All other functions are available for use within normalisation rules.
-optional C<eval{length('v123^a') == 3}> tag at B<beginning of format> will be
-perl code that is evaluated before producing output (value of field will be
-interpolated before that)
+=head2 data_structure
-=item *
+Return data structure
+
+ my $ds = WebPAC::Normalize::data_structure(
+ lookup => $lookup_hash,
+ row => $row,
+ rules => $normalize_pl_config,
+ marc_encoding => 'utf-8',
+ config => $config,
+ load_row_coderef => sub {
+ my ($database,$input,$mfn) = @_;
+ $store->load_row( database => $database, input => $input, id => $mfn );
+ },
+ );
-optional C<filter{filter_name}> at B<begining of format> will apply perl
-code defined as code ref on format after field substitution to producing
-output
+Options C<row>, C<rules> and C<log> are mandatory while all
+other are optional.
-There is one built-in filter called C<regex> which can be use like this:
+C<load_row_coderef> is closure only used when executing lookups, so they will
+die if it's not defined.
- filter{regex(s/foo/bar/)}
+This function will B<die> if normalizastion can't be evaled.
-=item *
+Since this function isn't exported you have to call it with
+C<WebPAC::Normalize::data_structure>.
-optional C<lookup{...}> will be then performed. See C<WebPAC::Lookups>.
+=cut
-=item *
+my $load_row_coderef;
-at end, optional C<format>s rules are resolved. Format rules are similar to
-C<sprintf> and can also contain C<lookup{...}> which is performed after
-values are inserted in format.
+sub data_structure {
+ my $arg = {@_};
-=back
+ die "need row argument" unless ($arg->{row});
+ die "need normalisation argument" unless ($arg->{rules});
-This also describes order in which transformations are applied (eval,
-filter, lookup, format) which is important to undestand when deciding how to
-solve your data mungling and normalisation process.
+ _set_lookup( $arg->{lookup} ) if defined($arg->{lookup});
+ _set_ds( $arg->{row} );
+ _set_config( $arg->{config} ) if defined($arg->{config});
+ _clean_ds( %{ $arg } );
+ $load_row_coderef = $arg->{load_row_coderef};
+ no strict 'subs';
+ no warnings 'redefine';
+ eval "$arg->{rules};";
+ die "error evaling $arg->{rules}: $@\n" if ($@);
+ return _get_ds();
+}
+=head2 _set_ds
-=head1 FUNCTIONS
+Set current record hash
-=head2 new
+ _set_ds( $rec );
-Create new normalisation object
+=cut
- my $n = new WebPAC::Normalize::Something(
- filter => {
- 'filter_name_1' => sub {
- # filter code
- return length($_);
- }, ...
- },
- db => $db_obj,
- lookup_regex => $lookup->regex,
- lookup => $lookup_obj,
- prefix => 'foobar',
- );
+my $rec;
-Parametar C<filter> defines user supplied snippets of perl code which can
-be use with C<filter{...}> notation.
+sub _set_ds {
+ $rec = shift or die "no record hash";
+ $WebPAC::Normalize::MARC::rec = $rec;
+}
-C<prefix> is used to form filename for database record (to support multiple
-source files which are joined in one database).
+=head2
-Recommended parametar C<lookup_regex> is used to enable parsing of lookups
-in structures. If you pass this parametar, you must also pass C<lookup>
-which is C<WebPAC::Lookup> object.
+ my $rec = _get_rec();
=cut
-sub new {
- my $class = shift;
- my $self = {@_};
- bless($self, $class);
-
- my $r = $self->{'lookup_regex'} ? 1 : 0;
- my $l = $self->{'lookup'} ? 1 : 0;
+sub _get_rec { $rec };
- my $log = $self->_get_logger();
+=head2 _set_config
- # those two must be in pair
- if ( ($r & $l) != ($r || $l) ) {
- my $log = $self->_get_logger();
- $log->logdie("lookup_regex and lookup must be in pair");
- }
+Set current config hash
- $log->logdie("lookup must be WebPAC::Lookup object") if ($self->{'lookup'} && ! $self->{'lookup'}->isa('WebPAC::Lookup'));
+ _set_config( $config );
- $log->warn("no prefix defined. please check that!") unless ($self->{'prefix'});
+Magic keys are:
- $log->debug("using lookup regex: ", $self->{lookup_regex}) if ($r && $l);
+=over 4
- if (! $self->{filter} || ! $self->{filter}->{regex}) {
- $log->debug("adding built-in filter regex");
- $self->{filter}->{regex} = sub {
- my ($val, $regex) = @_;
- eval "\$val =~ $regex";
- return $val;
- };
- }
+=item _
- $self ? return $self : return undef;
-}
+Code of current database
-=head2 all_tags
+=item _mfn
-Returns all tags in document in specified order
+Current MFN
- my $sorted_tags = $self->all_tags();
+=back
=cut
-sub all_tags {
- my $self = shift;
+my $config;
- if (! $self->{_tags_by_order}) {
+sub _set_config {
+ $config = shift;
+}
- my $log = $self->_get_logger;
- # sanity check
- $log->logdie("can't find self->{inport_xml}->{indexer}") unless ($self->{import_xml}->{indexer});
+=head2 _get_ds
- my @tags = keys %{ $self->{'import_xml'}->{'indexer'}};
- $log->debug("unsorted tags: " . join(", ", @tags));
+Return hash formatted as data structure
- @tags = sort { $self->_sort_by_order } @tags;
+ my $ds = _get_ds();
- $log->debug("sorted tags: " . join(",", @tags) );
+=cut
- $self->{_tags_by_order} = \@tags;
- }
+my $out;
- return $self->{_tags_by_order};
+sub _get_ds {
+#warn "## out = ",dump($out);
+ return $out;
}
+=head2 _clean_ds
+Clean data structure hash for next record
-=head2 data_structure
-
-Create in-memory data structure which represents normalized layout from
-C<conf/normalize/*.xml>.
+ _clean_ds();
-This structures are used to produce output.
+=cut
- my $ds = $webpac->data_structure($rec);
+sub _clean_ds {
+ my $a = {@_};
+ $out = undef;
+ WebPAC::Normalize::MARC::_clean();
+}
-=cut
+=head2 _set_lookup
-sub data_structure {
- my $self = shift;
+Set current lookup hash
- my $log = $self->_get_logger();
+ _set_lookup( $lookup );
- my $rec = shift;
- $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);
+=cut
- $log->debug("data_structure rec = ", sub { Dumper($rec) });
+my $lookup;
- $log->logdie("need unique ID (mfn) in field 000 of record " . Dumper($rec) ) unless (defined($rec->{'000'}));
+sub _set_lookup {
+ $lookup = shift;
+}
- my $id = $rec->{'000'}->[0] || $log->logdie("field 000 isn't array!");
+=head2 _get_lookup
- my $cache_file;
+Get current lookup hash
- if ($self->{'db'}) {
- my $ds = $self->{'db'}->load_ds( id => $id, prefix => $self->{prefix} );
- $log->debug("load_ds( rec = ", sub { Dumper($rec) }, ") = ", sub { Dumper($ds) });
- return $ds if ($ds);
- $log->debug("cache miss, creating");
- }
+ my $lookup = _get_lookup();
- my $tags = $self->all_tags();
+=cut
- $log->debug("tags: ",sub { join(", ",@{ $tags }) });
+sub _get_lookup {
+ return $lookup;
+}
- my $ds;
+=head2 _set_load_row
- foreach my $field (@{ $tags }) {
+Setup code reference which will return L<data_structure> from
+L<WebPAC::Store>
- my $row;
+ _set_load_row(sub {
+ my ($database,$input,$mfn) = @_;
+ $store->load_row( database => $database, input => $input, id => $mfn );
+ });
-#print "field $field [",$self->{'tag'},"] = ",Dumper($self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}});
+=cut
- foreach my $tag (@{$self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}}) {
- my $format;
+sub _set_load_row {
+ my $coderef = shift;
+ confess "argument isn't CODE" unless ref($coderef) eq 'CODE';
- $log->logdie("expected tag HASH and got $tag") unless (ref($tag) eq 'HASH');
- $format = $tag->{'value'} || $tag->{'content'};
+ $load_row_coderef = $coderef;
+}
- my @v;
- if ($self->{'lookup_regex'} && $format =~ $self->{'lookup_regex'}) {
- @v = $self->_rec_to_arr($rec,$format,'fill_in');
- } else {
- @v = $self->_rec_to_arr($rec,$format,'parse');
- }
- if (! @v) {
- $log->debug("$field <",$self->{tag},"> format: $format no values");
- next;
- } else {
- $log->debug("$field <",$self->{tag},"> format: $format values: ", join(",", @v));
- }
+=head2 _debug
- if ($tag->{'sort'}) {
- @v = $self->sort_arr(@v);
- }
+Change level of debug warnings
- # use format?
- if ($tag->{'format_name'}) {
- @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v;
- }
+ _debug( 2 );
- # delimiter will join repeatable fields
- if ($tag->{'delimiter'}) {
- @v = ( join($tag->{'delimiter'}, @v) );
- }
+=cut
- # default types
- my @types = qw(display search);
- # override by type attribute
- @types = ( $tag->{'type'} ) if ($tag->{'type'});
+sub _debug {
+ my $l = shift;
+ return $debug unless defined($l);
+ warn "debug level $l",$/ if ($l > 0);
+ $debug = $l;
+ $WebPAC::Normalize::MARC::debug = $debug;
+}
- foreach my $type (@types) {
- # append to previous line?
- $log->debug("tag $field / $type [",sub { join(",",@v) }, "] ", $row->{'append'} || 'no append');
- if ($tag->{'append'}) {
+=head1 Functions to create C<data_structure>
- # I will delimit appended part with
- # delimiter (or ,)
- my $d = $tag->{'delimiter'};
- # default delimiter
- $d ||= " ";
+Those functions generally have to first in your normalization file.
- my $last = pop @{$row->{$type}};
- $d = "" if (! $last);
- $last .= $d . join($d, @v);
- push @{$row->{$type}}, $last;
+=head2 to
- } else {
- push @{$row->{$type}}, @v;
- }
- }
+Generic way to set values for some name
+ to('field-name', 'name-value' => rec('200','a') );
- }
+There are many helpers defined below which might be easier to use.
- if ($row) {
- $row->{'tag'} = $field;
+=cut
- # TODO: name_sigular, name_plural
- my $name = $self->{'import_xml'}->{'indexer'}->{$field}->{'name'};
- my $row_name = $name ? $self->_x($name) : $field;
+sub to {
+ my $type = shift or confess "need type -- BUG?";
+ my $name = shift or confess "needs name as first argument";
+ my @o = grep { defined($_) && $_ ne '' } @_;
+ return unless (@o);
+ $out->{$name}->{$type} = \@o;
+}
- # post-sort all values in field
- if ($self->{'import_xml'}->{'indexer'}->{$field}->{'sort'}) {
- $log->warn("sort at field tag not implemented");
- }
+=head2 search_display
- $ds->{$row_name} = $row;
+Define output for L<search> and L<display> at the same time
- $log->debug("row $field: ",sub { Dumper($row) });
- }
+ search_display('Title', rec('200','a') );
- }
+=cut
- $self->{'db'}->save_ds(
- id => $id,
- ds => $ds,
- prefix => $self->{prefix},
- ) if ($self->{'db'});
+sub search_display {
+ my $name = shift or die "search_display needs name as first argument";
+ my @o = grep { defined($_) && $_ ne '' } @_;
+ return unless (@o);
+ $out->{$name}->{search} = \@o;
+ $out->{$name}->{display} = \@o;
+}
- $log->debug("ds: ", sub { Dumper($ds) });
+=head2 tag
- $log->logconfess("data structure returned is not array any more!") if wantarray;
+Old name for L<search_display>, it will probably be removed at one point.
- return $ds;
+=cut
+sub tag {
+ search_display( @_ );
}
-=head2 parse
+=head2 display
+
+Define output just for I<display>
-Perform smart parsing of string, skipping delimiters for fields which aren't
-defined. It can also eval code in format starting with C<eval{...}> and
-return output or nothing depending on eval code.
+ @v = display('Title', rec('200','a') );
- my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i);
+=cut
-Filters are implemented here. While simple form of filters looks like this:
+sub display { to( 'display', @_ ) }
- filter{name_of_filter}
+=head2 search
-but, filters can also have variable number of parametars like this:
+Prepare values just for I<search>
- filter{name_of_filter(param,param,param)}
+ @v = search('Title', rec('200','a') );
=cut
-my $warn_once;
+sub search { to( 'search', @_ ) }
-sub parse {
- my $self = shift;
+=head2 sorted
- my ($rec, $format_utf8, $i, $rec_size) = @_;
+Insert into lists which will be automatically sorted
- return if (! $format_utf8);
+ sorted('Title', rec('200','a') );
- my $log = $self->_get_logger();
+=cut
- $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);
+sub sorted { to( 'sorted', @_ ) }
- $i = 0 if (! $i);
- my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'});
+=head1 Functions to extract data from input
- my @out;
+This function should be used inside functions to create C<data_structure> described
+above.
- $log->debug("format: $format [$i]");
+=head2 _pack_subfields_hash
- my $eval_code;
- # remove eval{...} from beginning
- $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);
+ @subfields = _pack_subfields_hash( $h );
+ $subfields = _pack_subfields_hash( $h, 1 );
- my $filter_name;
- # remove filter{...} from beginning
- $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);
+Return each subfield value in array or pack them all together and return scalar
+with subfields (denoted by C<^>) and values.
- # did we found any (att all) field from format in row?
- my $found_any;
- # prefix before first field which we preserve it $found_any
- my $prefix;
+=cut
+
+sub _pack_subfields_hash {
- my $f_step = 1;
+ warn "## _pack_subfields_hash( ",dump(@_), " )\n" if ($debug > 1);
- while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) {
+ my ($h,$include_subfields) = @_;
- my $del = $1 || '';
- $prefix = $del if ($f_step == 1);
+ # sanity and ease of use
+ return $h if (ref($h) ne 'HASH');
- my $fld_type = lc($2);
+ if ( defined($h->{subfields}) ) {
+ my $sfs = delete $h->{subfields} || die "no subfields?";
+ my @out;
+ while (@$sfs) {
+ my $sf = shift @$sfs;
+ push @out, '^' . $sf if ($include_subfields);
+ my $o = shift @$sfs;
+ if ($o == 0 && ref( $h->{$sf} ) ne 'ARRAY' ) {
+ # single element subfields are not arrays
+#warn "====> $sf $o / $#$sfs ", dump( $sfs, $h->{$sf} ), "\n";
- # repeatable index
- my $r = $i;
- if ($fld_type eq 's') {
- if ($found_any->{'v'}) {
- $r = 0;
+ push @out, $h->{$sf};
} else {
- return;
+#warn "====> $sf $o / $#$sfs ", dump( $sfs, $h->{$sf} ), "\n";
+ push @out, $h->{$sf}->[$o];
}
}
-
- my $found = 0;
- my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found,$rec_size);
-
- if ($found) {
- $found_any->{$fld_type} += $found;
-
- # we will skip delimiter before first occurence of field!
- push @out, $del unless($found_any->{$fld_type} == 1);
- push @out, $tmp if ($tmp);
+ if ($include_subfields) {
+ return join('', @out);
+ } else {
+ return @out;
+ }
+ } else {
+ if ($include_subfields) {
+ my $out = '';
+ foreach my $sf (sort keys %$h) {
+ if (ref($h->{$sf}) eq 'ARRAY') {
+ $out .= '^' . $sf . join('^' . $sf, @{ $h->{$sf} });
+ } else {
+ $out .= '^' . $sf . $h->{$sf};
+ }
+ }
+ return $out;
+ } else {
+ # FIXME this should probably be in alphabetical order instead of hash order
+ values %{$h};
}
- $f_step++;
}
+}
- # test if any fields found?
- return if (! $found_any->{'v'} && ! $found_any->{'s'});
+=head2 rec1
- my $out = join('',@out);
+Return all values in some field
- if ($out) {
- # add rest of format (suffix)
- $out .= $format;
+ @v = rec1('200')
- # add prefix if not there
- $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/);
+TODO: order of values is probably same as in source data, need to investigate that
- $log->debug("result: $out");
- }
+=cut
- if ($eval_code) {
- my $eval = $self->fill_in($rec,$eval_code,$i) || return;
- $log->debug("about to eval{$eval} format: $out");
- return if (! $self->_eval($eval));
- }
-
- if ($filter_name) {
- my @filter_args;
- if ($filter_name =~ s/(\w+)\((.*)\)/$1/) {
- @filter_args = split(/,/, $2);
- }
- if ($self->{'filter'}->{$filter_name}) {
- $log->debug("about to filter{$filter_name} format: $out with arguments: ", join(",", @filter_args));
- unshift @filter_args, $out;
- $out = $self->{'filter'}->{$filter_name}->(@filter_args);
- return unless(defined($out));
- $log->debug("filter result: $out");
- } elsif (! $warn_once->{$filter_name}) {
- $log->warn("trying to use undefined filter $filter_name");
- $warn_once->{$filter_name}++;
+sub rec1 {
+ my $f = shift;
+ warn "rec1($f) = ", dump( $rec->{$f} ), $/ if ($debug > 1);
+ return unless (defined($rec) && defined($rec->{$f}));
+ warn "rec1($f) = ", dump( $rec->{$f} ), $/ if ($debug > 1);
+ if (ref($rec->{$f}) eq 'ARRAY') {
+ my @out;
+ foreach my $h ( @{ $rec->{$f} } ) {
+ if (ref($h) eq 'HASH') {
+ push @out, ( _pack_subfields_hash( $h ) );
+ } else {
+ push @out, $h;
+ }
}
+ return @out;
+ } elsif( defined($rec->{$f}) ) {
+ return $rec->{$f};
}
+}
- return $out;
+=head2 rec2
+
+Return all values in specific field and subfield
+
+ @v = rec2('200','a')
+
+=cut
+
+sub rec2 {
+ my $f = shift;
+ return unless (defined($rec && $rec->{$f}));
+ my $sf = shift;
+ warn "rec2($f,$sf) = ", dump( $rec->{$f} ), $/ if ($debug > 1);
+ return map {
+ if (ref($_->{$sf}) eq 'ARRAY') {
+ @{ $_->{$sf} };
+ } else {
+ $_->{$sf};
+ }
+ } grep { ref($_) eq 'HASH' && defined $_->{$sf} } @{ $rec->{$f} };
}
-=head2 fill_in
+=head2 rec
-Workhourse of all: takes record from in-memory structure of database and
-strings with placeholders and returns string or array of with substituted
-values from record.
+syntaxtic sugar for
- my $text = $webpac->fill_in($rec,'v250^a');
+ @v = rec('200')
+ @v = rec('200','a')
-Optional argument is ordinal number for repeatable fields. By default,
-it's assume to be first repeatable field (fields are perl array, so first
-element is 0).
-Following example will read second value from repeatable field.
+If rec() returns just single value, it will
+return scalar, not array.
- my $text = $webpac->fill_in($rec,'Title: v250^a',1);
+=cut
-This function B<does not> perform parsing of format to inteligenty skip
-delimiters before fields which aren't used.
+sub rec {
+ my @out;
+ if ($#_ == 0) {
+ @out = rec1(@_);
+ } elsif ($#_ == 1) {
+ @out = rec2(@_);
+ }
+ if ($#out == 0 && ! wantarray) {
+ return $out[0];
+ } elsif (@out) {
+ return @out;
+ } else {
+ return '';
+ }
+}
-This method will automatically decode UTF-8 string to local code page
-if needed.
+=head2 frec
-There is optional parametar C<$record_size> which can be used to get sizes of
-all C<field^subfield> combinations in this format.
+Returns first value from field
- my $text = $webpac->fill_in($rec,'got: v900^a v900^x',0,\$rec_size);
+ $v = frec('200');
+ $v = frec('200','a');
=cut
-sub fill_in {
- my $self = shift;
+sub frec {
+ my @out = rec(@_);
+ warn "rec(",dump(@_),") has more than one return value, ignoring\n" if $#out > 0;
+ return shift @out;
+}
- my $log = $self->_get_logger();
+=head2 frec_eq
- my ($rec,$format,$i,$rec_size) = @_;
+=head2 frec_ne
- $log->logconfess("need data record") unless ($rec);
- $log->logconfess("need format to parse") unless($format);
+Check if first values from two fields are same or different
- # iteration (for repeatable fields)
- $i ||= 0;
+ if ( frec_eq( 900 => 'a', 910 => 'c' ) ) {
+ # values are same
+ } else {
+ # values are different
+ }
- $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999));
+Strictly speaking C<frec_eq> and C<frec_ne> wouldn't be needed if you
+could write something like:
- # FIXME remove for speedup?
- $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);
+ if ( frec( '900','a' ) eq frec( '910','c' ) ) {
+ # yada tada
+ }
- if (utf8::is_utf8($format)) {
- $format = $self->_x($format);
- }
+but you can't since our parser L<WebPAC::Parser> will remove all whitespaces
+in order to parse text and create invalid function C<eqfrec>.
- my $found = 0;
- my $just_single = 1;
+=cut
- my $eval_code;
- # remove eval{...} from beginning
- $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);
+sub frec_eq {
+ my ( $f1,$sf1, $f2, $sf2 ) = @_;
+ return (rec( $f1, $sf1 ))[0] eq (rec( $f2, $sf2 ))[0];
+}
- my $filter_name;
- # remove filter{...} from beginning
- $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);
+sub frec_ne {
+ return ! frec_eq( @_ );
+}
- {
- # fix warnings
- no warnings 'uninitialized';
+=head2 regex
- # do actual replacement of placeholders
- # repeatable fields
- if ($format =~ s/v(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,$i,\$found,$rec_size)/ges) {
- $just_single = 0;
- }
+Apply regex to some or all values
- # non-repeatable fields
- if ($format =~ s/s(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,0,\$found,$rec_size)/ges) {
- return if ($i > 0 && $just_single);
- }
- }
+ @v = regex( 's/foo/bar/g', @v );
- if ($found) {
- $log->debug("format: $format");
- if ($eval_code) {
- my $eval = $self->fill_in($rec,$eval_code,$i);
- return if (! $self->_eval($eval));
- }
- if ($filter_name && $self->{'filter'}->{$filter_name}) {
- $log->debug("filter '$filter_name' for $format");
- $format = $self->{'filter'}->{$filter_name}->($format);
- return unless(defined($format));
- $log->debug("filter result: $format");
- }
- # do we have lookups?
- if ($self->{'lookup'}) {
- if ($self->{'lookup'}->can('lookup')) {
- my @lookup = $self->{lookup}->lookup($format);
- $log->debug("lookup $format", join(", ", @lookup));
- return @lookup;
- } else {
- $log->warn("Have lookup object but can't invoke lookup method");
- }
- } else {
- return $format;
- }
- } else {
- return;
+=cut
+
+sub regex {
+ my $r = shift;
+ my @out;
+ #warn "r: $r\n", dump(\@_);
+ foreach my $t (@_) {
+ next unless ($t);
+ eval "\$t =~ $r";
+ push @out, $t if ($t && $t ne '');
}
+ return @out;
}
+=head2 prefix
-=head2 _rec_to_arr
-
-Similar to C<parse> and C<fill_in>, but returns array of all repeatable fields. Usable
-for fields which have lookups, so they shouldn't be parsed but rather
-C<paste>d or C<fill_id>ed. Last argument is name of operation: C<paste> or C<fill_in>.
+Prefix all values with a string
- my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]','paste');
+ @v = prefix( 'my_', @v );
=cut
-sub _rec_to_arr {
- my $self = shift;
+sub prefix {
+ my $p = shift;
+ return @_ unless defined( $p );
+ return map { $p . $_ } grep { defined($_) } @_;
+}
- my ($rec, $format_utf8, $code) = @_;
+=head2 suffix
- my $log = $self->_get_logger();
+suffix all values with a string
- $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);
- return if (! $format_utf8);
+ @v = suffix( '_my', @v );
- $log->debug("using $code on $format_utf8");
+=cut
- my $i = 0;
- my $max = 0;
- my @arr;
- my $rec_size = {};
+sub suffix {
+ my $s = shift;
+ return @_ unless defined( $s );
+ return map { $_ . $s } grep { defined($_) } @_;
+}
- while ($i <= $max) {
- my @v = $self->$code($rec,$format_utf8,$i++,\$rec_size);
- if ($rec_size) {
- foreach my $f (keys %{ $rec_size }) {
- $max = $rec_size->{$f} if ($rec_size->{$f} > $max);
- }
- $log->debug("max set to $max");
- undef $rec_size;
- }
- if (@v) {
- push @arr, @v;
- } else {
- push @arr, '' if ($max > $i);
- }
- }
+=head2 surround
+
+surround all values with a two strings
+
+ @v = surround( 'prefix_', '_suffix', @v );
- $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);
+=cut
- return @arr;
+sub surround {
+ my $p = shift;
+ my $s = shift;
+ $p = '' unless defined( $p );
+ $s = '' unless defined( $s );
+ return map { $p . $_ . $s } grep { defined($_) } @_;
}
+=head2 first
-=head2 get_data
+Return first element
-Returns value from record.
+ $v = first( @v );
- my $text = $self->get_data(\$rec,$f,$sf,$i,\$found,\$rec_size);
+=cut
-Required arguments are:
+sub first {
+ my $r = shift;
+ return $r;
+}
-=over 8
+=head2 lookup
-=item C<$rec>
+Consult lookup hashes for some value
-record reference
+ @v = lookup(
+ sub {
+ 'ffkk/peri/mfn'.rec('000')
+ },
+ 'ffkk','peri','200-a-200-e',
+ sub {
+ first(rec(200,'a')).' '.first(rec('200','e'))
+ }
+ );
-=item C<$f>
+Code like above will be B<automatically generated> using L<WebPAC::Parse> from
+normal lookup definition in C<conf/lookup/something.pl> which looks like:
+
+ lookup(
+ # which results to return from record recorded in lookup
+ sub { 'ffkk/peri/mfn' . rec('000') },
+ # from which database and input
+ 'ffkk','peri',
+ # such that following values match
+ sub { first(rec(200,'a')) . ' ' . first(rec('200','e')) },
+ # if this part is missing, we will try to match same fields
+ # from lookup record and current one, or you can override
+ # which records to use from current record using
+ sub { rec('900','x') . ' ' . rec('900','y') },
+ )
+
+You can think about this lookup as SQL (if that helps):
+
+ select
+ sub { what }
+ from
+ database, input
+ where
+ sub { filter from lookuped record }
+ having
+ sub { optional filter on current record }
+
+Easy as pie, right?
-field
+=cut
-=item C<$sf>
+sub lookup {
+ my ($what, $database, $input, $key, $having) = @_;
-optional subfield
+ confess "lookup needs 5 arguments: what, database, input, key, having\n" unless ($#_ == 4);
-=item C<$i>
+ warn "## lookup ($database, $input, $key)", $/ if ($debug > 1);
+ return unless (defined($lookup->{$database}->{$input}->{$key}));
-index offset for repeatable values ( 0 ... $rec_size->{'400^a'} )
+ confess "lookup really need load_row_coderef added to data_structure\n" unless ($load_row_coderef);
-=item C<$found>
+ my $mfns;
+ my @having = $having->();
-optional variable that will be incremeted if preset
+ warn "## having = ", dump( @having ) if ($debug > 2);
-=item C<$rec_size>
+ foreach my $h ( @having ) {
+ if (defined($lookup->{$database}->{$input}->{$key}->{$h})) {
+ warn "lookup for $database/$input/$key/$h return ",dump($lookup->{$database}->{$input}->{$key}->{$h}),"\n" if ($debug);
+ $mfns->{$_}++ foreach keys %{ $lookup->{$database}->{$input}->{$key}->{$h} };
+ }
+ }
-hash to hold maximum occurances of C<field^subfield> combinations
-(which can be accessed using keys in same format)
+ return unless ($mfns);
-=back
+ my @mfns = sort keys %$mfns;
-Returns value or empty string, updates C<$found> and C<rec_size>
-if present.
+ warn "# lookup loading $database/$input/$key mfn ", join(",",@mfns)," having ",dump(@having),"\n" if ($debug);
-=cut
+ my $old_rec = $rec;
+ my @out;
-sub get_data {
- my $self = shift;
+ foreach my $mfn (@mfns) {
+ $rec = $load_row_coderef->( $database, $input, $mfn );
- my ($rec,$f,$sf,$i,$found,$cache) = @_;
+ warn "got $database/$input/$mfn = ", dump($rec), $/ if ($debug);
- return '' unless ($$rec->{$f} && ref($$rec->{$f}) eq 'ARRAY');
+ my @vals = $what->();
- if (defined($$cache)) {
- $$cache->{ $f . ( $sf ? '^' . $sf : '' ) } ||= scalar @{ $$rec->{$f} };
+ push @out, ( @vals );
+
+ warn "lookup for mfn $mfn returned ", dump(@vals), $/ if ($debug);
}
- return '' unless ($$rec->{$f}->[$i]);
+# if (ref($lookup->{$k}) eq 'ARRAY') {
+# return @{ $lookup->{$k} };
+# } else {
+# return $lookup->{$k};
+# }
- {
- no strict 'refs';
- if (defined($sf)) {
- $$found++ if (defined($$found) && $$rec->{$f}->[$i]->{$sf});
- return $$rec->{$f}->[$i]->{$sf};
- } else {
- $$found++ if (defined($$found));
- # it still might have subfields, just
- # not specified, so we'll dump some debug info
- if ($$rec->{$f}->[$i] =~ /HASH/o) {
- my $out;
- foreach my $k (keys %{$$rec->{$f}->[$i]}) {
- my $v = $$rec->{$f}->[$i]->{$k};
- $out .= '$' . $k .':' . $v if ($v);
- }
- return $out;
- } else {
- return $$rec->{$f}->[$i];
- }
- }
+ $rec = $old_rec;
+
+ warn "## lookup returns = ", dump(@out), $/ if ($debug);
+
+ if ($#out == 0) {
+ return $out[0];
+ } else {
+ return @out;
}
}
+=head2 save_into_lookup
-=head2 apply_format
+Save value into lookup. It associates current database, input
+and specific keys with one or more values which will be
+associated over MFN.
-Apply format specified in tag with C<format_name="name"> and
-C<format_delimiter=";;">.
+MFN will be extracted from first occurence current of field 000
+in current record, or if it doesn't exist from L<_set_config> C<_mfn>.
- my $text = $webpac->apply_format($format_name,$format_delimiter,$data);
+ my $nr = save_into_lookup($database,$input,$key,sub {
+ # code which produce one or more values
+ });
-Formats can contain C<lookup{...}> if you need them.
+It returns number of items saved.
+
+This function shouldn't be called directly, it's called from code created by
+L<WebPAC::Parser>.
=cut
-sub apply_format {
- my $self = shift;
+sub save_into_lookup {
+ my ($database,$input,$key,$coderef) = @_;
+ die "save_into_lookup needs database" unless defined($database);
+ die "save_into_lookup needs input" unless defined($input);
+ die "save_into_lookup needs key" unless defined($key);
+ die "save_into_lookup needs CODE" unless ( defined($coderef) && ref($coderef) eq 'CODE' );
+
+ warn "## save_into_lookup rec = ", dump($rec), " config = ", dump($config), $/ if ($debug > 2);
- my ($name,$delimiter,$data) = @_;
+ my $mfn =
+ defined($rec->{'000'}->[0]) ? $rec->{'000'}->[0] :
+ defined($config->{_mfn}) ? $config->{_mfn} :
+ die "mfn not defined or zero";
- my $log = $self->_get_logger();
+ my $nr = 0;
- if (! $self->{'import_xml'}->{'format'}->{$name}) {
- $log->warn("<format name=\"$name\"> is not defined in ",$self->{'import_xml_file'});
- return $data;
+ foreach my $v ( $coderef->() ) {
+ $lookup->{$database}->{$input}->{$key}->{$v}->{$mfn}++;
+ warn "# saved lookup $database/$input/$key [$v] $mfn\n" if ($debug > 1);
+ $nr++;
}
- $log->warn("no delimiter for format $name") if (! $delimiter);
+ return $nr;
+}
+
+=head2 config
+
+Consult config values stored in C<config.yml>
+
+ # return database code (key under databases in yaml)
+ $database_code = config(); # use _ from hash
+ $database_name = config('name');
+ $database_input_name = config('input name');
- my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'");
+Up to three levels are supported.
- my @data = split(/\Q$delimiter\E/, $data);
+=cut
+
+sub config {
+ return unless ($config);
+
+ my $p = shift;
- my $out = sprintf($format, @data);
- $log->debug("using format $name [$format] on $data to produce: $out");
+ $p ||= '';
- if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) {
- return $self->{'lookup'}->lookup($out);
+ my $v;
+
+ warn "### getting config($p)\n" if ($debug > 1);
+
+ my @p = split(/\s+/,$p);
+ if ($#p < 0) {
+ $v = $config->{ '_' }; # special, database code
} else {
- return $out;
+
+ my $c = dclone( $config );
+
+ foreach my $k (@p) {
+ warn "### k: $k c = ",dump($c),$/ if ($debug > 1);
+ if (ref($c) eq 'ARRAY') {
+ $c = shift @$c;
+ warn "config($p) taking first occurence of '$k', probably not what you wanted!\n";
+ last;
+ }
+
+ if (! defined($c->{$k}) ) {
+ $c = undef;
+ last;
+ } else {
+ $c = $c->{$k};
+ }
+ }
+ $v = $c if ($c);
+
}
+ warn "## config( '$p' ) = ",dump( $v ),$/ if ($v && $debug);
+ warn "config( '$p' ) is empty\n" if (! $v);
+
+ return $v;
}
-=head2 sort_arr
+=head2 id
+
+Returns unique id of this record
-Sort array ignoring case and html in data
+ $id = id();
- my @sorted = $webpac->sort_arr(@unsorted);
+Returns C<42/2> for 2nd occurence of MFN 42.
=cut
-sub sort_arr {
- my $self = shift;
+sub id {
+ my $mfn = $config->{_mfn} || die "no _mfn in config data";
+ return $mfn . ( WebPAC::Normalize::MARC::_created_marc_records() || '' );
+}
+
+=head2 join_with
- my $log = $self->_get_logger();
+Joins walues with some delimiter
- # FIXME add Schwartzian Transformation?
+ $v = join_with(", ", @v);
- my @sorted = sort {
- $a =~ s#<[^>]+/*>##;
- $b =~ s#<[^>]+/*>##;
- lc($b) cmp lc($a)
- } @_;
- $log->debug("sorted values: ",sub { join(", ",@sorted) });
+=cut
- return @sorted;
+sub join_with {
+ my $d = shift;
+ warn "### join_with('$d',",dump(@_),")\n" if ($debug > 2);
+ my $v = join($d, grep { defined($_) && $_ ne '' } @_);
+ return '' unless defined($v);
+ return $v;
}
+=head2 split_rec_on
-=head1 INTERNAL METHODS
+Split record subfield on some regex and take one of parts out
-=head2 _sort_by_order
+ $a_before_semi_column =
+ split_rec_on('200','a', /\s*;\s*/, $part);
-Sort xml tags data structure accoding to C<order=""> attribute.
+C<$part> is optional number of element. First element is
+B<1>, not 0!
+
+If there is no C<$part> parameter or C<$part> is 0, this function will
+return all values produced by splitting.
=cut
-sub _sort_by_order {
- my $self = shift;
+sub split_rec_on {
+ die "split_rec_on need (fld,sf,regex[,part]" if ($#_ < 2);
- my $va = $self->{'import_xml'}->{'indexer'}->{$a}->{'order'} ||
- $self->{'import_xml'}->{'indexer'}->{$a};
- my $vb = $self->{'import_xml'}->{'indexer'}->{$b}->{'order'} ||
- $self->{'import_xml'}->{'indexer'}->{$b};
+ my ($fld, $sf, $regex, $part) = @_;
+ warn "### regex ", ref($regex), $regex, $/ if ($debug > 2);
- return $va <=> $vb;
-}
+ my @r = rec( $fld, $sf );
+ my $v = shift @r;
+ warn "### first rec($fld,$sf) = ",dump($v),$/ if ($debug > 2);
+
+ return '' if ( ! defined($v) || $v =~ /^\s*$/);
-=head2 _x
+ my @s = split( $regex, $v );
+ warn "## split_rec_on($fld,$sf,$regex,$part) = ",dump(@s),$/ if ($debug > 1);
+ if ($part && $part > 0) {
+ return $s[ $part - 1 ];
+ } else {
+ return @s;
+ }
+}
-Convert strings from C<conf/normalize/*.xml> encoding into application
-specific encoding (optinally specified using C<code_page> to C<new>
-constructor).
+my $hash;
- my $text = $n->_x('normalize text string');
+=head2 set
-This is a stub so that other modules doesn't have to implement it.
+ set( key => 'value' );
=cut
-sub _x {
- my $self = shift;
- return shift;
-}
+sub set {
+ my ($k,$v) = @_;
+ warn "## set ( $k => ", dump($v), " )", $/ if ( $debug );
+ $hash->{$k} = $v;
+};
+=head2 get
-=head1 AUTHOR
+ get( 'key' );
-Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>
+=cut
-=head1 COPYRIGHT & LICENSE
+sub get {
+ my $k = shift || return;
+ my $v = $hash->{$k};
+ warn "## get $k = ", dump( $v ), $/ if ( $debug );
+ return $v;
+}
-Copyright 2005 Dobrica Pavlinusic, All Rights Reserved.
+=head2 count
-This program is free software; you can redistribute it and/or modify it
-under the same terms as Perl itself.
+ if ( count( @result ) == 1 ) {
+ # do something if only 1 result is there
+ }
=cut
-1; # End of WebPAC::Normalize
+sub count {
+ warn "## count ",dump(@_),$/ if ( $debug );
+ return @_ . '';
+}
+
+# END
+1;