--- trunk/lib/WebPAC/Normalize.pm 2006/01/08 22:09:33 373 +++ trunk/lib/WebPAC/Normalize.pm 2006/07/03 14:32:40 572 @@ -1,758 +1,689 @@ package WebPAC::Normalize; +use Exporter 'import'; +@EXPORT = qw/ + _set_rec _set_lookup + _get_ds _clean_ds + _debug + + tag search display + marc marc_indicators marc_repeatable_subfield + marc_compose marc_leader + + rec1 rec2 rec + regex prefix suffix surround + first lookup join_with + + split_rec_on +/; use warnings; use strict; -use blib; -use WebPAC::Common; -use base 'WebPAC::Common'; -use Data::Dumper; + +#use base qw/WebPAC::Common/; +use Data::Dump qw/dump/; +use Encode qw/from_to/; + +# debugging warn(s) +my $debug = 0; + =head1 NAME -WebPAC::Normalize - data mungling for normalisation +WebPAC::Normalize - describe normalisaton rules using sets =head1 VERSION -Version 0.08 +Version 0.09 =cut -our $VERSION = '0.08'; +our $VERSION = '0.09'; =head1 SYNOPSIS -This package contains code that mungle data to produce normalized format. - -It contains several assumptions: - -=over - -=item * - -format of fields is defined using C notation for repeatable fields -or C for single (or first) value, where C<123> is field number and -C is subfield. - -=item * - -source data records (C<$rec>) have unique identifiers in field C<000> +This module uses C files to perform normalisation +from input records using perl functions which are specialized for set +processing. + +Sets are implemented as arrays, and normalisation file is valid perl, which +means that you check it's validity before running WebPAC using +C. + +Normalisation can generate multiple output normalized data. For now, supported output +types (on the left side of definition) are: C, C, C and +C. -=item * +=head1 FUNCTIONS -optional C tag at B will be -perl code that is evaluated before producing output (value of field will be -interpolated before that) +Functions which start with C<_> are private and used by WebPAC internally. +All other functions are available for use within normalisation rules. -=item * +=head2 data_structure -optional C at B will apply perl -code defined as code ref on format after field substitution to producing -output +Return data structure -There is one built-in filter called C which can be use like this: + my $ds = WebPAC::Normalize::data_structure( + lookup => $lookup->lookup_hash, + row => $row, + rules => $normalize_pl_config, + marc_encoding => 'utf-8', + ); - filter{regex(s/foo/bar/)} +Options C, C, C and C are mandatory while all +other are optional. -=item * +This function will B if normalizastion can't be evaled. -optional C will be then performed. See C. +Since this function isn't exported you have to call it with +C. -=item * +=cut -at end, optional Cs rules are resolved. Format rules are similar to -C and can also contain C 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. + no strict 'subs'; + _set_lookup( $arg->{lookup} ); + _set_rec( $arg->{row} ); + _clean_ds( %{ $arg } ); + eval "$arg->{rules}"; + die "error evaling $arg->{rules}: $@\n" if ($@); + return _get_ds(); +} +=head2 _set_rec +Set current record hash -=head1 FUNCTIONS + _set_rec( $rec ); -=head2 new +=cut -Create new normalisation object +my $rec; - 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', - ); +sub _set_rec { + $rec = shift or die "no record hash"; +} -Parametar C defines user supplied snippets of perl code which can -be use with C notation. +=head2 _get_ds -C is used to form filename for database record (to support multiple -source files which are joined in one database). +Return hash formatted as data structure -Recommended parametar C is used to enable parsing of lookups -in structures. If you pass this parametar, you must also pass C -which is C object. + my $ds = _get_ds(); =cut -sub new { - my $class = shift; - my $self = {@_}; - bless($self, $class); +my ($out,$marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators); - my $r = $self->{'lookup_regex'} ? 1 : 0; - my $l = $self->{'lookup'} ? 1 : 0; - - my $log = $self->_get_logger(); - - # 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"); - } +sub _get_ds { + return $out; +} - $log->logdie("lookup must be WebPAC::Lookup object") if ($self->{'lookup'} && ! $self->{'lookup'}->isa('WebPAC::Lookup')); +=head2 _clean_ds - $log->warn("no prefix defined. please check that!") unless ($self->{'prefix'}); +Clean data structure hash for next record - $log->debug("using lookup regex: ", $self->{lookup_regex}) if ($r && $l); + _clean_ds(); - 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; - }; - } +=cut - $self ? return $self : return undef; +sub _clean_ds { + my $a = {@_}; + ($out,$marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators) = (); + $marc_encoding = $a->{marc_encoding}; } +=head2 _set_lookup -=head2 data_structure +Set current lookup hash -Create in-memory data structure which represents normalized layout from -C. + _set_lookup( $lookup ); -This structures are used to produce output. +=cut - my $ds = $webpac->data_structure($rec); +my $lookup; -=cut +sub _set_lookup { + $lookup = shift; +} -sub data_structure { - my $self = shift; +=head2 _get_marc_fields - my $log = $self->_get_logger(); +Get all fields defined by calls to C - my $rec = shift; - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); + $marc->add_fields( WebPAC::Normalize:_get_marc_fields() ); - $log->debug("data_structure rec = ", sub { Dumper($rec) }); +We are using I which detect repeatable fields only from +sequence of field/subfield data generated by normalization. - $log->logdie("need unique ID (mfn) in field 000 of record " . Dumper($rec) ) unless (defined($rec->{'000'})); +Repeatable field is created when there is second occurence of same subfield or +if any of indicators are different. - my $id = $rec->{'000'}->[0] || $log->logdie("field 000 isn't array!"); +This is sane for most cases. Something like: - my $cache_file; + 900a-1 900b-1 900c-1 + 900a-2 900b-2 + 900a-3 - 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"); - } +will be created from any combination of: - my @sorted_tags; - if ($self->{tags_by_order}) { - @sorted_tags = @{$self->{tags_by_order}}; - } else { - @sorted_tags = sort { $self->_sort_by_order } keys %{$self->{'import_xml'}->{'indexer'}}; - $self->{tags_by_order} = \@sorted_tags; - } + 900a-1 900a-2 900a-3 900b-1 900b-2 900c-1 - my $ds; +and following rules: - $log->debug("tags: ",sub { join(", ",@sorted_tags) }); + marc('900','a', rec('200','a') ); + marc('900','b', rec('200','b') ); + marc('900','c', rec('200','c') ); - foreach my $field (@sorted_tags) { +which might not be what you have in mind. If you need repeatable subfield, +define it using C like this: - my $row; +.... -#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 _get_marc_fields { - $log->logdie("expected tag HASH and got $tag") unless (ref($tag) eq 'HASH'); - $format = $tag->{'value'} || $tag->{'content'}; + return if (! $marc_record || ref($marc_record) ne 'ARRAY' || $#{ $marc_record } < 0); - 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)); - } + # first, sort all existing fields + # XXX might not be needed, but modern perl might randomize elements in hash + my @sorted_marc_record = sort { + $a->[0] . ( $a->[3] || '' ) cmp $b->[0] . ( $b->[3] || '') + } @{ $marc_record }; - if ($tag->{'sort'}) { - @v = $self->sort_arr(@v); - } + @sorted_marc_record = @{ $marc_record }; ### FIXME disable sorting + + # output marc fields + my @m; - # use format? - if ($tag->{'format_name'}) { - @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v; - } + # count unique field-subfields (used for offset when walking to next subfield) + my $u; + map { $u->{ $_->[0] . ( $_->[3] || '') }++ } @sorted_marc_record; + + if ($debug) { + warn "## marc_repeatable_subfield ", dump( $marc_repeatable_subfield ), $/; + warn "## marc_record ", dump( $marc_record ), $/; + warn "## sorted_marc_record ", dump( \@sorted_marc_record ), $/; + warn "## subfield count ", dump( $u ), $/; + } - # delimiter will join repeatable fields - if ($tag->{'delimiter'}) { - @v = ( join($tag->{'delimiter'}, @v) ); - } + my $len = $#sorted_marc_record; + my $visited; + my $i = 0; + my $field; - # default types - my @types = qw(display search); - # override by type attribute - @types = ( $tag->{'type'} ) if ($tag->{'type'}); - - foreach my $type (@types) { - # append to previous line? - $log->debug("tag $field / $type [",sub { join(",",@v) }, "] ", $row->{'append'} || 'no append'); - if ($tag->{'append'}) { - - # I will delimit appended part with - # delimiter (or ,) - my $d = $tag->{'delimiter'}; - # default delimiter - $d ||= " "; - - my $last = pop @{$row->{$type}}; - $d = "" if (! $last); - $last .= $d . join($d, @v); - push @{$row->{$type}}, $last; - - } else { - push @{$row->{$type}}, @v; - } - } + foreach ( 0 .. $len ) { + # find next element which isn't visited + while ($visited->{$i}) { + $i = ($i + 1) % ($len + 1); + } + + # mark it visited + $visited->{$i}++; + + my $row = $sorted_marc_record[$i]; + + # field and subfield which is key for + # marc_repeatable_subfield and u + my $fsf = $row->[0] . ( $row->[3] || '' ); + + if ($debug > 1) { + + print "### field so far [", $#$field, "] : ", dump( $field ), " ", $field ? 'T' : 'F', $/; + print "### this [$i]: ", dump( $row ),$/; + print "### sf: ", $row->[3], " vs ", $field->[3], + $marc_repeatable_subfield->{ $row->[0] . $row->[3] } ? ' (repeatable)' : '', $/, + if ($#$field >= 0); } - if ($row) { - $row->{'tag'} = $field; + # if field exists + if ( $#$field >= 0 ) { + if ( + $row->[0] ne $field->[0] || # field + $row->[1] ne $field->[1] || # i1 + $row->[2] ne $field->[2] # i2 + ) { + push @m, $field; + warn "## saved/1 ", dump( $field ),$/ if ($debug); + $field = $row; + + } elsif ( + ( $row->[3] lt $field->[-2] ) # subfield which is not next (e.g. a after c) + || + ( $row->[3] eq $field->[-2] && # same subfield, but not repeatable + ! $marc_repeatable_subfield->{ $fsf } + ) + ) { + push @m, $field; + warn "## saved/2 ", dump( $field ),$/ if ($debug); + $field = $row; - # TODO: name_sigular, name_plural - my $name = $self->{'import_xml'}->{'indexer'}->{$field}->{'name'}; - my $row_name = $name ? $self->_x($name) : $field; - - # post-sort all values in field - if ($self->{'import_xml'}->{'indexer'}->{$field}->{'sort'}) { - $log->warn("sort at field tag not implemented"); + } else { + # append new subfields to existing field + push @$field, ( $row->[3], $row->[4] ); } - - $ds->{$row_name} = $row; - - $log->debug("row $field: ",sub { Dumper($row) }); + } else { + # insert first field + $field = $row; } + if (! $marc_repeatable_subfield->{ $fsf }) { + # make step to next subfield + $i = ($i + $u->{ $fsf } ) % ($len + 1); + } } - $self->{'db'}->save_ds( - id => $id, - ds => $ds, - prefix => $self->{prefix}, - ) if ($self->{'db'}); - - $log->debug("ds: ", sub { Dumper($ds) }); - - $log->logconfess("data structure returned is not array any more!") if wantarray; - - return $ds; + if ($#$field >= 0) { + push @m, $field; + warn "## saved/3 ", dump( $field ),$/ if ($debug); + } + return @m; } -=head2 parse +=head2 _debug -Perform smart parsing of string, skipping delimiters for fields which aren't -defined. It can also eval code in format starting with C and -return output or nothing depending on eval code. +Change level of debug warnings - my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i); + _debug( 2 ); -Filters are implemented here. While simple form of filters looks like this: +=cut - filter{name_of_filter} +sub _debug { + my $l = shift; + return $debug unless defined($l); + warn "debug level $l",$/ if ($l > 0); + $debug = $l; +} -but, filters can also have variable number of parametars like this: +=head1 Functions to create C - filter{name_of_filter(param,param,param)} +Those functions generally have to first in your normalization file. -=cut +=head2 tag -my $warn_once; +Define new tag for I and I. -sub parse { - my $self = shift; + tag('Title', rec('200','a') ); - my ($rec, $format_utf8, $i, $rec_size) = @_; - return if (! $format_utf8); +=cut - my $log = $self->_get_logger(); +sub tag { + my $name = shift or die "tag needs name as first argument"; + my @o = grep { defined($_) && $_ ne '' } @_; + return unless (@o); + $out->{$name}->{tag} = $name; + $out->{$name}->{search} = \@o; + $out->{$name}->{display} = \@o; +} - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); +=head2 display - $i = 0 if (! $i); +Define tag just for I - my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'}); + @v = display('Title', rec('200','a') ); - my @out; +=cut - $log->debug("format: $format [$i]"); +sub display { + my $name = shift or die "display needs name as first argument"; + my @o = grep { defined($_) && $_ ne '' } @_; + return unless (@o); + $out->{$name}->{tag} = $name; + $out->{$name}->{display} = \@o; +} - my $eval_code; - # remove eval{...} from beginning - $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s); +=head2 search - my $filter_name; - # remove filter{...} from beginning - $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s); +Prepare values just for I - # 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; + @v = search('Title', rec('200','a') ); - my $f_step = 1; +=cut - while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) { +sub search { + my $name = shift or die "search needs name as first argument"; + my @o = grep { defined($_) && $_ ne '' } @_; + return unless (@o); + $out->{$name}->{tag} = $name; + $out->{$name}->{search} = \@o; +} - my $del = $1 || ''; - $prefix = $del if ($f_step == 1); +=head2 marc_leader - my $fld_type = lc($2); +Setup fields within MARC leader or get leader - # repeatable index - my $r = $i; - if ($fld_type eq 's') { - if ($found_any->{'v'}) { - $r = 0; - } else { - return; - } - } + marc_leader('05','c'); + my $leader = marc_leader(); - my $found = 0; - my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found,$rec_size); +=cut - if ($found) { - $found_any->{$fld_type} += $found; +sub marc_leader { + my ($offset,$value) = @_; - # we will skip delimiter before first occurence of field! - push @out, $del unless($found_any->{$fld_type} == 1); - push @out, $tmp; - } - $f_step++; + if ($offset) { + $out->{' leader'}->{ $offset } = $value; + } else { + return $out->{' leader'}; } +} - # test if any fields found? - return if (! $found_any->{'v'} && ! $found_any->{'s'}); +=head2 marc - my $out = join('',@out); +Save value for MARC field - if ($out) { - # add rest of format (suffix) - $out .= $format; + marc('900','a', rec('200','a') ); + marc('001', rec('000') ); - # add prefix if not there - $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/); +=cut - $log->debug("result: $out"); - } +sub marc { + my $f = shift or die "marc needs field"; + die "marc field must be numer" unless ($f =~ /^\d+$/); - 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)); + my $sf; + if ($f >= 10) { + $sf = shift or die "marc needs subfield"; } - - 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}++; + + foreach (@_) { + my $v = $_; # make var read-write for Encode + next unless (defined($v) && $v !~ /^\s*$/); + from_to($v, 'iso-8859-2', $marc_encoding) if ($marc_encoding); + my ($i1,$i2) = defined($marc_indicators->{$f}) ? @{ $marc_indicators->{$f} } : (' ',' '); + if (defined $sf) { + push @{ $marc_record }, [ $f, $i1, $i2, $sf => $v ]; + } else { + push @{ $marc_record }, [ $f, $v ]; } } - - return $out; } -=head2 fill_in +=head2 marc_repeatable_subfield -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. +Save values for MARC repetable subfield - my $text = $webpac->fill_in($rec,'v250^a'); + marc_repeatable_subfield('910', 'z', rec('909') ); -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. +=cut - my $text = $webpac->fill_in($rec,'Title: v250^a',1); +sub marc_repeatable_subfield { + my ($f,$sf) = @_; + die "marc_repeatable_subfield need field and subfield!\n" unless ($f && $sf); + $marc_repeatable_subfield->{ $f . $sf }++; + marc(@_); +} -This function B perform parsing of format to inteligenty skip -delimiters before fields which aren't used. +=head2 marc_indicators -This method will automatically decode UTF-8 string to local code page -if needed. +Set both indicators for MARC field -There is optional parametar C<$record_size> which can be used to get sizes of -all C combinations in this format. + marc_indicators('900', ' ', 1); - my $text = $webpac->fill_in($rec,'got: v900^a v900^x',0,\$rec_size); +Any indicator value other than C<0-9> will be treated as undefined. =cut -sub fill_in { - my $self = shift; - - my $log = $self->_get_logger(); +sub marc_indicators { + my $f = shift || die "marc_indicators need field!\n"; + my ($i1,$i2) = @_; + die "marc_indicators($f, ...) need i1!\n" unless(defined($i1)); + die "marc_indicators($f, $i1, ...) need i2!\n" unless(defined($i2)); - my ($rec,$format,$i,$rec_size) = @_; - - $log->logconfess("need data record") unless ($rec); - $log->logconfess("need format to parse") unless($format); + $i1 = ' ' if ($i1 !~ /^\d$/); + $i2 = ' ' if ($i2 !~ /^\d$/); + @{ $marc_indicators->{$f} } = ($i1,$i2); +} - # iteration (for repeatable fields) - $i ||= 0; +=head2 marc_compose - $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999)); +Save values for each MARC subfield explicitly - # FIXME remove for speedup? - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); + marc_compose('900', + 'a', rec('200','a') + 'b', rec('201','a') + 'a', rec('200','b') + 'c', rec('200','c') + ); - if (utf8::is_utf8($format)) { - $format = $self->_x($format); - } +=cut - my $found = 0; - my $just_single = 1; +sub marc_compose { + my $f = shift or die "marc_compose needs field"; + die "marc_compose field must be numer" unless ($f =~ /^\d+$/); - my $eval_code; - # remove eval{...} from beginning - $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s); + my ($i1,$i2) = defined($marc_indicators->{$f}) ? @{ $marc_indicators->{$f} } : (' ',' '); + my $m = [ $f, $i1, $i2 ]; - my $filter_name; - # remove filter{...} from beginning - $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s); + while (@_) { + my $sf = shift or die "marc_compose $f needs subfield"; + my $v = shift; - # 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; + next unless (defined($v) && $v !~ /^\s*$/); + from_to($v, 'iso-8859-2', $marc_encoding) if ($marc_encoding); + push @$m, ( $sf, $v ); + warn "## ++ marc_compose($f,$sf,$v) ", dump( $m ),$/ if ($debug > 1); } - # 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); - } + warn "## marc_compose(d) ", dump( $m ),$/ if ($debug > 1); - 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; - } + push @{ $marc_record }, $m if ($#{$m} > 2); } -=head2 _rec_to_arr +=head1 Functions to extract data from input -Similar to C and C, but returns array of all repeatable fields. Usable -for fields which have lookups, so they shouldn't be parsed but rather -Cd or Ced. Last argument is name of operation: C or C. +This function should be used inside functions to create C described +above. - my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]','paste'); +=head2 rec1 -=cut +Return all values in some field -sub _rec_to_arr { - my $self = shift; + @v = rec1('200') - my ($rec, $format_utf8, $code) = @_; +TODO: order of values is probably same as in source data, need to investigate that - my $log = $self->_get_logger(); - - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); - return if (! $format_utf8); - - $log->debug("using $code on $format_utf8"); +=cut - my $i = 0; - my $max = 0; - my @arr; - my $rec_size = {}; - - 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); +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') { + return map { + if (ref($_) eq 'HASH') { + values %{$_}; + } else { + $_; } - $log->debug("max set to $max"); - undef $rec_size; - } - if (@v) { - push @arr, @v; - } else { - push @arr, ''; - } + } @{ $rec->{$f} }; + } elsif( defined($rec->{$f}) ) { + return $rec->{$f}; } - - $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr); - - return @arr; } +=head2 rec2 -=head2 get_data +Return all values in specific field and subfield -Returns value from record. + @v = rec2('200','a') - my $text = $self->get_data(\$rec,$f,$sf,$i,\$found,\$rec_size); - -Required arguments are: - -=over 8 +=cut -=item C<$rec> +sub rec2 { + my $f = shift; + return unless (defined($rec && $rec->{$f})); + my $sf = shift; + return map { $_->{$sf} } grep { ref($_) eq 'HASH' && $_->{$sf} } @{ $rec->{$f} }; +} -record reference +=head2 rec -=item C<$f> +syntaxtic sugar for -field + @v = rec('200') + @v = rec('200','a') -=item C<$sf> +=cut -optional subfield +sub rec { + if ($#_ == 0) { + return rec1(@_); + } elsif ($#_ == 1) { + return rec2(@_); + } +} -=item C<$i> +=head2 regex -index offset for repeatable values ( 0 ... $rec_size->{'400^a'} ) +Apply regex to some or all values -=item C<$found> + @v = regex( 's/foo/bar/g', @v ); -optional variable that will be incremeted if preset +=cut -=item C<$rec_size> +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; +} -hash to hold maximum occurances of C combinations -(which can be accessed using keys in same format) +=head2 prefix -=back +Prefix all values with a string -Returns value or empty string, updates C<$found> and C -if present. + @v = prefix( 'my_', @v ); =cut -sub get_data { - my $self = shift; +sub prefix { + my $p = shift or die "prefix needs string as first argument"; + return map { $p . $_ } grep { defined($_) } @_; +} - my ($rec,$f,$sf,$i,$found,$cache) = @_; +=head2 suffix - return '' unless ($$rec->{$f} && ref($$rec->{$f}) eq 'ARRAY'); +suffix all values with a string - if (defined($$cache)) { - $$cache->{ $f . ( $sf ? '^' . $sf : '' ) } ||= scalar @{ $$rec->{$f} }; - } + @v = suffix( '_my', @v ); - return '' unless ($$rec->{$f}->[$i]); +=cut - { - 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]}) { - $out .= '$' . $k .':' . $$rec->{$f}->[$i]->{$k}." "; - } - return $out; - } else { - return $$rec->{$f}->[$i]; - } - } - } +sub suffix { + my $s = shift or die "suffix needs string as first argument"; + return map { $_ . $s } grep { defined($_) } @_; } +=head2 surround -=head2 apply_format +surround all values with a two strings -Apply format specified in tag with C and -C. - - my $text = $webpac->apply_format($format_name,$format_delimiter,$data); - -Formats can contain C if you need them. + @v = surround( 'prefix_', '_suffix', @v ); =cut -sub apply_format { - my $self = shift; - - my ($name,$delimiter,$data) = @_; - - my $log = $self->_get_logger(); - - if (! $self->{'import_xml'}->{'format'}->{$name}) { - $log->warn(" is not defined in ",$self->{'import_xml_file'}); - return $data; - } - - $log->warn("no delimiter for format $name") if (! $delimiter); +sub surround { + my $p = shift or die "surround need prefix as first argument"; + my $s = shift or die "surround needs suffix as second argument"; + return map { $p . $_ . $s } grep { defined($_) } @_; +} - my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'"); +=head2 first - my @data = split(/\Q$delimiter\E/, $data); +Return first element - my $out = sprintf($format, @data); - $log->debug("using format $name [$format] on $data to produce: $out"); + $v = first( @v ); - if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) { - return $self->{'lookup'}->lookup($out); - } else { - return $out; - } +=cut +sub first { + my $r = shift; + return $r; } -=head2 sort_arr +=head2 lookup -Sort array ignoring case and html in data +Consult lookup hashes for some value - my @sorted = $webpac->sort_arr(@unsorted); + @v = lookup( $v ); + @v = lookup( @v ); =cut -sub sort_arr { - my $self = shift; - - my $log = $self->_get_logger(); - - # FIXME add Schwartzian Transformation? - - my @sorted = sort { - $a =~ s#<[^>]+/*>##; - $b =~ s#<[^>]+/*>##; - lc($b) cmp lc($a) - } @_; - $log->debug("sorted values: ",sub { join(", ",@sorted) }); - - return @sorted; +sub lookup { + my $k = shift or return; + return unless (defined($lookup->{$k})); + if (ref($lookup->{$k}) eq 'ARRAY') { + return @{ $lookup->{$k} }; + } else { + return $lookup->{$k}; + } } +=head2 join_with -=head1 INTERNAL METHODS - -=head2 _sort_by_order +Joins walues with some delimiter -Sort xml tags data structure accoding to C attribute. + $v = join_with(", ", @v); =cut -sub _sort_by_order { - my $self = shift; - - 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}; - - return $va <=> $vb; +sub join_with { + my $d = shift; + return join($d, grep { defined($_) && $_ ne '' } @_); } -=head2 _x +=head2 split_rec_on -Convert strings from C encoding into application -specific encoding (optinally specified using C to C -constructor). +Split record subfield on some regex and take one of parts out - my $text = $n->_x('normalize text string'); + $a_before_semi_column = + split_rec_on('200','a', /\s*;\s*/, $part); -This is a stub so that other modules doesn't have to implement it. +C<$part> is optional number of element. First element is +B<1>, not 0! -=cut - -sub _x { - my $self = shift; - return shift; -} +If there is no C<$part> parameter or C<$part> is 0, this function will +return all values produced by splitting. +=cut -=head1 AUTHOR - -Dobrica Pavlinusic, C<< >> +sub split_rec_on { + die "split_rec_on need (fld,sf,regex[,part]" if ($#_ < 2); -=head1 COPYRIGHT & LICENSE + my ($fld, $sf, $regex, $part) = @_; + warn "### regex ", ref($regex), $regex, $/ if ($debug > 2); -Copyright 2005 Dobrica Pavlinusic, All Rights Reserved. + my @r = rec( $fld, $sf ); + my $v = shift @r; + warn "### first rec($fld,$sf) = ",dump($v),$/ if ($debug > 2); -This program is free software; you can redistribute it and/or modify it -under the same terms as Perl itself. + return '' if( ! defined($v) || $v =~ /^\s*$/); -=cut + 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; + } +} -1; # End of WebPAC::Normalize +# END +1;