/[webpac2]/trunk/lib/WebPAC/Normalize.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Diff of /trunk/lib/WebPAC/Normalize.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 371 by dpavlin, Sun Jan 8 21:16:27 2006 UTC revision 712 by dpavlin, Tue Sep 26 10:23:04 2006 UTC
# Line 1  Line 1 
1  package WebPAC::Normalize;  package WebPAC::Normalize;
2    use Exporter 'import';
3    @EXPORT = qw/
4            _set_rec _set_lookup
5            _get_ds _clean_ds
6            _debug
7            _pack_subfields_hash
8    
9            tag search display
10            marc marc_indicators marc_repeatable_subfield
11            marc_compose marc_leader
12            marc_duplicate marc_remove
13            marc_original_order
14    
15            rec1 rec2 rec
16            regex prefix suffix surround
17            first lookup join_with
18            save_into_lookup
19    
20            split_rec_on
21    /;
22    
23  use warnings;  use warnings;
24  use strict;  use strict;
25  use blib;  
26  use WebPAC::Common;  #use base qw/WebPAC::Common/;
27  use base 'WebPAC::Common';  use Data::Dump qw/dump/;
28  use Data::Dumper;  use Storable qw/dclone/;
29    
30    # debugging warn(s)
31    my $debug = 0;
32    
33    
34  =head1 NAME  =head1 NAME
35    
36  WebPAC::Normalize - data mungling for normalisation  WebPAC::Normalize - describe normalisaton rules using sets
37    
38  =head1 VERSION  =head1 VERSION
39    
40  Version 0.08  Version 0.20
41    
42  =cut  =cut
43    
44  our $VERSION = '0.08';  our $VERSION = '0.20';
45    
46  =head1 SYNOPSIS  =head1 SYNOPSIS
47    
48  This package contains code that mungle data to produce normalized format.  This module uses C<conf/normalize/*.pl> files to perform normalisation
49    from input records using perl functions which are specialized for set
50    processing.
51    
52    Sets are implemented as arrays, and normalisation file is valid perl, which
53    means that you check it's validity before running WebPAC using
54    C<perl -c normalize.pl>.
55    
56    Normalisation can generate multiple output normalized data. For now, supported output
57    types (on the left side of definition) are: C<tag>, C<display>, C<search> and
58    C<marc>.
59    
60  It contains several assumptions:  =head1 FUNCTIONS
61    
62  =over  Functions which start with C<_> are private and used by WebPAC internally.
63    All other functions are available for use within normalisation rules.
64    
65  =item *  =head2 data_structure
66    
67  format of fields is defined using C<v123^a> notation for repeatable fields  Return data structure
 or C<s123^a> for single (or first) value, where C<123> is field number and  
 C<a> is subfield.  
68    
69  =item *    my $ds = WebPAC::Normalize::data_structure(
70            lookup => $lookup_variable,
71            row => $row,
72            rules => $normalize_pl_config,
73            marc_encoding => 'utf-8',
74            config => $config,
75      );
76    
77  source data records (C<$rec>) have unique identifiers in field C<000>  Options C<row>, C<rules> and C<log> are mandatory while all
78    other are optional.
79    
80  =item *  This function will B<die> if normalizastion can't be evaled.
81    
82  optional C<eval{length('v123^a') == 3}> tag at B<beginning of format> will be  Since this function isn't exported you have to call it with
83  perl code that is evaluated before producing output (value of field will be  C<WebPAC::Normalize::data_structure>.
 interpolated before that)  
84    
85  =item *  =cut
86    
87  optional C<filter{filter_name}> at B<begining of format> will apply perl  sub data_structure {
88  code defined as code ref on format after field substitution to producing          my $arg = {@_};
 output  
89    
90  There is one built-in filter called C<regex> which can be use like this:          die "need row argument" unless ($arg->{row});
91            die "need normalisation argument" unless ($arg->{rules});
92    
93    filter{regex(s/foo/bar/)}          no strict 'subs';
94            _set_lookup( $arg->{lookup} ) if (defined( $arg->{lookup} ));
95            _set_rec( $arg->{row} );
96            _set_config( $arg->{config} ) if (defined( $arg->{config} ));
97            _clean_ds( %{ $arg } );
98            eval "$arg->{rules}";
99            die "error evaling $arg->{rules}: $@\n" if ($@);
100    
101  =item *          return _get_ds();
102    }
103    
104  optional C<lookup{...}> will be then performed. See C<WebPAC::Lookups>.  =head2 _set_rec
105    
106  =item *  Set current record hash
107    
108  at end, optional C<format>s rules are resolved. Format rules are similar to    _set_rec( $rec );
 C<sprintf> and can also contain C<lookup{...}> which is performed after  
 values are inserted in format.  
109    
110  =back  =cut
111    
112  This also describes order in which transformations are applied (eval,  my $rec;
 filter, lookup, format) which is important to undestand when deciding how to  
 solve your data mungling and normalisation process.  
113    
114    sub _set_rec {
115            $rec = shift or die "no record hash";
116    }
117    
118    =head2 _set_config
119    
120    Set current config hash
121    
122  =head1 FUNCTIONS    _set_config( $config );
123    
124  =head2 new  Magic keys are:
125    
126  Create new normalisation object  =over 4
127    
128    my $n = new WebPAC::Normalize::Something(  =item _
         filter => {  
                 'filter_name_1' => sub {  
                         # filter code  
                         return length($_);  
                 }, ...  
         },  
         db => $db_obj,  
         lookup_regex => $lookup->regex,  
         lookup => $lookup_obj,  
         prefix => 'foobar',  
   );  
129    
130  Parametar C<filter> defines user supplied snippets of perl code which can  Code of current database
 be use with C<filter{...}> notation.  
131    
132  C<prefix> is used to form filename for database record (to support multiple  =item _mfn
 source files which are joined in one database).  
133    
134  Recommended parametar C<lookup_regex> is used to enable parsing of lookups  Current MFN
135  in structures. If you pass this parametar, you must also pass C<lookup>  
136  which is C<WebPAC::Lookup> object.  =back
137    
138  =cut  =cut
139    
140  sub new {  my $config;
         my $class = shift;  
         my $self = {@_};  
         bless($self, $class);  
141    
142          my $r = $self->{'lookup_regex'} ? 1 : 0;  sub _set_config {
143          my $l = $self->{'lookup'} ? 1 : 0;          $config = shift;
144    }
145    
146          my $log = $self->_get_logger();  =head2 _get_ds
147    
148          # those two must be in pair  Return hash formatted as data structure
         if ( ($r & $l) != ($r || $l) ) {  
                 my $log = $self->_get_logger();  
                 $log->logdie("lookup_regex and lookup must be in pair");  
         }  
149    
150          $log->logdie("lookup must be WebPAC::Lookup object") if ($self->{'lookup'} && ! $self->{'lookup'}->isa('WebPAC::Lookup'));    my $ds = _get_ds();
151    
152          $log->warn("no prefix defined. please check that!") unless ($self->{'prefix'});  =cut
153    
154          $log->debug("using lookup regex: ", $self->{lookup_regex}) if ($r && $l);  my ($out, $marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators);
155    my ($marc_record_offset, $marc_fetch_offset) = (0, 0);
156    
157          if (! $self->{filter} || ! $self->{filter}->{regex}) {  sub _get_ds {
158                  $log->debug("adding built-in filter regex");          return $out;
159                  $self->{filter}->{regex} = sub {  }
                         my ($val, $regex) = @_;  
                         eval "\$val =~ $regex";  
                         return $val;  
                 };  
         }  
160    
161          $self ? return $self : return undef;  =head2 _clean_ds
162    
163    Clean data structure hash for next record
164    
165      _clean_ds();
166    
167    =cut
168    
169    sub _clean_ds {
170            my $a = {@_};
171            ($out,$marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators) = ();
172            ($marc_record_offset, $marc_fetch_offset) = (0,0);
173            $marc_encoding = $a->{marc_encoding};
174  }  }
175    
176    =head2 _set_lookup
177    
178  =head2 data_structure  Set current lookup hash
179    
180  Create in-memory data structure which represents normalized layout from    _set_lookup( $lookup );
 C<conf/normalize/*.xml>.  
181    
182  This structures are used to produce output.  =cut
183    
184   my $ds = $webpac->data_structure($rec);  my $lookup;
185    
186    sub _set_lookup {
187            $lookup = shift;
188    }
189    
190    =head2 _get_lookup
191    
192    Get current lookup hash
193    
194      my $lookup = _get_lookup();
195    
196  =cut  =cut
197    
198  sub data_structure {  sub _get_lookup {
199          my $self = shift;          return $lookup;
200    }
201    
202          my $log = $self->_get_logger();  =head2 _get_marc_fields
203    
204          my $rec = shift;  Get all fields defined by calls to C<marc>
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
205    
206          $log->debug("data_structure rec = ", sub { Dumper($rec) });          $marc->add_fields( WebPAC::Normalize:_get_marc_fields() );
207    
208          $log->logdie("need unique ID (mfn) in field 000 of record " . Dumper($rec) ) unless (defined($rec->{'000'}));  We are using I<magic> which detect repeatable fields only from
209    sequence of field/subfield data generated by normalization.
210    
211          my $id = $rec->{'000'}->[0] || $log->logdie("field 000 isn't array!");  Repeatable field is created when there is second occurence of same subfield or
212    if any of indicators are different.
213    
214          my $cache_file;  This is sane for most cases. Something like:
215    
216          if ($self->{'db'}) {    900a-1 900b-1 900c-1
217                  my $ds = $self->{'db'}->load_ds( id => $id, prefix => $self->{prefix} );    900a-2 900b-2
218                  $log->debug("load_ds( rec = ", sub { Dumper($rec) }, ") = ", sub { Dumper($ds) });    900a-3
                 return $ds if ($ds);  
                 $log->debug("cache miss, creating");  
         }  
219    
220          my @sorted_tags;  will be created from any combination of:
221          if ($self->{tags_by_order}) {  
222                  @sorted_tags = @{$self->{tags_by_order}};    900a-1 900a-2 900a-3 900b-1 900b-2 900c-1
223          } else {  
224                  @sorted_tags = sort { $self->_sort_by_order } keys %{$self->{'import_xml'}->{'indexer'}};  and following rules:
225                  $self->{tags_by_order} = \@sorted_tags;  
226      marc('900','a', rec('200','a') );
227      marc('900','b', rec('200','b') );
228      marc('900','c', rec('200','c') );
229    
230    which might not be what you have in mind. If you need repeatable subfield,
231    define it using C<marc_repeatable_subfield> like this:
232    
233      marc_repeatable_subfield('900','a');
234      marc('900','a', rec('200','a') );
235      marc('900','b', rec('200','b') );
236      marc('900','c', rec('200','c') );
237    
238    will create:
239    
240      900a-1 900a-2 900a-3 900b-1 900c-1
241      900b-2
242    
243    There is also support for returning next or specific using:
244    
245      while (my $mf = WebPAC::Normalize:_get_marc_fields( fetch_next => 1 ) ) {
246            # do something with $mf
247      }
248    
249    will always return fields from next MARC record or
250    
251      my $mf = WebPAC::Normalize::_get_marc_fields( offset => 42 );
252    
253    will return 42th copy record (if it exists).
254    
255    =cut
256    
257    sub _get_marc_fields {
258    
259            my $arg = {@_};
260            warn "### _get_marc_fields arg: ", dump($arg), $/ if ($debug > 2);
261            my $offset = $marc_fetch_offset;
262            if ($arg->{offset}) {
263                    $offset = $arg->{offset};
264            } elsif($arg->{fetch_next}) {
265                    $marc_fetch_offset++;
266          }          }
267    
268          my $ds;          return if (! $marc_record || ref($marc_record) ne 'ARRAY');
269    
270          $log->debug("tags: ",sub { join(", ",@sorted_tags) });          warn "### full marc_record = ", dump( @{ $marc_record }), $/ if ($debug > 2);
271    
272          foreach my $field (@sorted_tags) {          my $marc_rec = $marc_record->[ $offset ];
273    
274                  my $row;          warn "## _get_marc_fields (at offset: $offset) -- marc_record = ", dump( @$marc_rec ), $/ if ($debug > 1);
275    
276  #print "field $field [",$self->{'tag'},"] = ",Dumper($self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}});          return if (! $marc_rec || ref($marc_rec) ne 'ARRAY' || $#{ $marc_rec } < 0);
277    
278                  foreach my $tag (@{$self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}}) {          # first, sort all existing fields
279                          my $format;          # XXX might not be needed, but modern perl might randomize elements in hash
280            my @sorted_marc_record = sort {
281                    $a->[0] . ( $a->[3] || '' ) cmp $b->[0] . ( $b->[3] || '')
282            } @{ $marc_rec };
283    
284                          $log->logdie("expected tag HASH and got $tag") unless (ref($tag) eq 'HASH');          @sorted_marc_record = @{ $marc_rec };   ### FIXME disable sorting
285                          $format = $tag->{'value'} || $tag->{'content'};          
286            # output marc fields
287            my @m;
288    
289                          my @v;          # count unique field-subfields (used for offset when walking to next subfield)
290                          if ($self->{'lookup_regex'} && $format =~ $self->{'lookup_regex'}) {          my $u;
291                                  @v = $self->fill_in_to_arr($rec,$format);          map { $u->{ $_->[0] . ( $_->[3] || '')  }++ } @sorted_marc_record;
292                          } else {  
293                                  @v = $self->parse_to_arr($rec,$format);          if ($debug) {
294                          }                  warn "## marc_repeatable_subfield = ", dump( $marc_repeatable_subfield ), $/ if ( $marc_repeatable_subfield );
295                          if (! @v) {                  warn "## marc_record[$offset] = ", dump( $marc_rec ), $/;
296                                  $log->debug("$field <",$self->{tag},"> format: $format no values");                  warn "## sorted_marc_record = ", dump( \@sorted_marc_record ), $/;
297  #                               next;                  warn "## subfield count = ", dump( $u ), $/;
298                          } else {          }
                                 $log->debug("$field <",$self->{tag},"> format: $format values: ", join(",", @v));  
                         }  
299    
300                          if ($tag->{'sort'}) {          my $len = $#sorted_marc_record;
301                                  @v = $self->sort_arr(@v);          my $visited;
302                          }          my $i = 0;
303            my $field;
304    
305                          # use format?          foreach ( 0 .. $len ) {
                         if ($tag->{'format_name'}) {  
                                 @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v;  
                         }  
306    
307                          # delimiter will join repeatable fields                  # find next element which isn't visited
308                          if ($tag->{'delimiter'}) {                  while ($visited->{$i}) {
309                                  @v = ( join($tag->{'delimiter'}, @v) );                          $i = ($i + 1) % ($len + 1);
310                          }                  }
311    
312                          # default types                  # mark it visited
313                          my @types = qw(display search);                  $visited->{$i}++;
                         # 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;  
314    
315                                  } else {                  my $row = dclone( $sorted_marc_record[$i] );
                                         push @{$row->{$type}}, @v;  
                                 }  
                         }  
316    
317                    # field and subfield which is key for
318                    # marc_repeatable_subfield and u
319                    my $fsf = $row->[0] . ( $row->[3] || '' );
320    
321                    if ($debug > 1) {
322    
323                            print "### field so far [", $#$field, "] : ", dump( $field ), " ", $field ? 'T' : 'F', $/;
324                            print "### this [$i]: ", dump( $row ),$/;
325                            print "### sf: ", $row->[3], " vs ", $field->[3],
326                                    $marc_repeatable_subfield->{ $row->[0] . $row->[3] } ? ' (repeatable)' : '', $/,
327                                    if ($#$field >= 0);
328    
329                  }                  }
330    
331                  if ($row) {                  # if field exists
332                          $row->{'tag'} = $field;                  if ( $#$field >= 0 ) {
333                            if (
334                                    $row->[0] ne $field->[0] ||             # field
335                                    $row->[1] ne $field->[1] ||             # i1
336                                    $row->[2] ne $field->[2]                # i2
337                            ) {
338                                    push @m, $field;
339                                    warn "## saved/1 ", dump( $field ),$/ if ($debug);
340                                    $field = $row;
341    
342                            } elsif (
343                                    ( $row->[3] lt $field->[-2] )           # subfield which is not next (e.g. a after c)
344                                    ||
345                                    ( $row->[3] eq $field->[-2] &&          # same subfield, but not repeatable
346                                            ! $marc_repeatable_subfield->{ $fsf }
347                                    )
348                            ) {
349                                    push @m, $field;
350                                    warn "## saved/2 ", dump( $field ),$/ if ($debug);
351                                    $field = $row;
352    
353                          # TODO: name_sigular, name_plural                          } else {
354                          my $name = $self->{'import_xml'}->{'indexer'}->{$field}->{'name'};                                  # append new subfields to existing field
355                          my $row_name = $name ? $self->_x($name) : $field;                                  push @$field, ( $row->[3], $row->[4] );
   
                         # post-sort all values in field  
                         if ($self->{'import_xml'}->{'indexer'}->{$field}->{'sort'}) {  
                                 $log->warn("sort at field tag not implemented");  
356                          }                          }
357                    } else {
358                            # insert first field
359                            $field = $row;
360                    }
361    
362                          $ds->{$row_name} = $row;                  if (! $marc_repeatable_subfield->{ $fsf }) {
363                            # make step to next subfield
364                          $log->debug("row $field: ",sub { Dumper($row) });                          $i = ($i + $u->{ $fsf } ) % ($len + 1);
365                  }                  }
366            }
367    
368            if ($#$field >= 0) {
369                    push @m, $field;
370                    warn "## saved/3 ", dump( $field ),$/ if ($debug);
371          }          }
372    
373          $self->{'db'}->save_ds(          return \@m;
374                  id => $id,  }
                 ds => $ds,  
                 prefix => $self->{prefix},  
         ) if ($self->{'db'});  
375    
376          $log->debug("ds: ", sub { Dumper($ds) });  =head2 _debug
377    
378          $log->logconfess("data structure returned is not array any more!") if wantarray;  Change level of debug warnings
379    
380          return $ds;    _debug( 2 );
381    
382  }  =cut
383    
384  =head2 parse  sub _debug {
385            my $l = shift;
386            return $debug unless defined($l);
387            warn "debug level $l",$/ if ($l > 0);
388            $debug = $l;
389    }
390    
391  Perform smart parsing of string, skipping delimiters for fields which aren't  =head1 Functions to create C<data_structure>
 defined. It can also eval code in format starting with C<eval{...}> and  
 return output or nothing depending on eval code.  
392    
393   my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i);  Those functions generally have to first in your normalization file.
394    
395  Filters are implemented here. While simple form of filters looks like this:  =head2 tag
396    
397    filter{name_of_filter}  Define new tag for I<search> and I<display>.
398    
399  but, filters can also have variable number of parametars like this:    tag('Title', rec('200','a') );
400    
   filter{name_of_filter(param,param,param)}  
401    
402  =cut  =cut
403    
404  my $warn_once;  sub tag {
405            my $name = shift or die "tag needs name as first argument";
406            my @o = grep { defined($_) && $_ ne '' } @_;
407            return unless (@o);
408            $out->{$name}->{tag} = $name;
409            $out->{$name}->{search} = \@o;
410            $out->{$name}->{display} = \@o;
411    }
412    
413  sub parse {  =head2 display
         my $self = shift;  
414    
415          my ($rec, $format_utf8, $i, $rec_size) = @_;  Define tag just for I<display>
416    
417          return if (! $format_utf8);    @v = display('Title', rec('200','a') );
418    
419          my $log = $self->_get_logger();  =cut
420    
421          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  sub display {
422            my $name = shift or die "display needs name as first argument";
423            my @o = grep { defined($_) && $_ ne '' } @_;
424            return unless (@o);
425            $out->{$name}->{tag} = $name;
426            $out->{$name}->{display} = \@o;
427    }
428    
429          $i = 0 if (! $i);  =head2 search
430    
431          my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'});  Prepare values just for I<search>
432    
433          my @out;    @v = search('Title', rec('200','a') );
434    
435          $log->debug("format: $format [$i]");  =cut
436    
437          my $eval_code;  sub search {
438          # remove eval{...} from beginning          my $name = shift or die "search needs name as first argument";
439          $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);          my @o = grep { defined($_) && $_ ne '' } @_;
440            return unless (@o);
441            $out->{$name}->{tag} = $name;
442            $out->{$name}->{search} = \@o;
443    }
444    
445          my $filter_name;  =head2 marc_leader
         # remove filter{...} from beginning  
         $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);  
446    
447          # did we found any (att all) field from format in row?  Setup fields within MARC leader or get leader
         my $found_any;  
         # prefix before first field which we preserve it $found_any  
         my $prefix;  
448    
449          my $f_step = 1;    marc_leader('05','c');
450      my $leader = marc_leader();
451    
452          while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) {  =cut
453    
454                  my $del = $1 || '';  sub marc_leader {
455                  $prefix = $del if ($f_step == 1);          my ($offset,$value) = @_;
456    
457                  my $fld_type = lc($2);          if ($offset) {
458                    $out->{' leader'}->{ $offset } = $value;
459            } else {
460                    return $out->{' leader'};
461            }
462    }
463    
464                  # repeatable index  =head2 marc
465                  my $r = $i;  
466                  if ($fld_type eq 's') {  Save value for MARC field
467                          if ($found_any->{'v'}) {  
468                                  $r = 0;    marc('900','a', rec('200','a') );
469                          } else {    marc('001', rec('000') );
                                 return;  
                         }  
                 }  
470    
471                  my $found = 0;  =cut
                 my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found,$rec_size);  
472    
473                  if ($found) {  sub marc {
474                          $found_any->{$fld_type} += $found;          my $f = shift or die "marc needs field";
475            die "marc field must be numer" unless ($f =~ /^\d+$/);
476    
477            my $sf;
478            if ($f >= 10) {
479                    $sf = shift or die "marc needs subfield";
480            }
481    
482                          # we will skip delimiter before first occurence of field!          foreach (@_) {
483                          push @out, $del unless($found_any->{$fld_type} == 1);                  my $v = $_;             # make var read-write for Encode
484                          push @out, $tmp;                  next unless (defined($v) && $v !~ /^\s*$/);
485                    my ($i1,$i2) = defined($marc_indicators->{$f}) ? @{ $marc_indicators->{$f} } : (' ',' ');
486                    if (defined $sf) {
487                            push @{ $marc_record->[ $marc_record_offset ] }, [ $f, $i1, $i2, $sf => $v ];
488                    } else {
489                            push @{ $marc_record->[ $marc_record_offset ] }, [ $f, $v ];
490                  }                  }
                 $f_step++;  
491          }          }
492    }
493    
494          # test if any fields found?  =head2 marc_repeatable_subfield
         return if (! $found_any->{'v'} && ! $found_any->{'s'});  
495    
496          my $out = join('',@out);  Save values for MARC repetable subfield
497    
498          if ($out) {    marc_repeatable_subfield('910', 'z', rec('909') );
                 # add rest of format (suffix)  
                 $out .= $format;  
499    
500                  # add prefix if not there  =cut
                 $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/);  
501    
502                  $log->debug("result: $out");  sub marc_repeatable_subfield {
503          }          my ($f,$sf) = @_;
504            die "marc_repeatable_subfield need field and subfield!\n" unless ($f && $sf);
505            $marc_repeatable_subfield->{ $f . $sf }++;
506            marc(@_);
507    }
508    
509    =head2 marc_indicators
510    
511    Set both indicators for MARC field
512    
513      marc_indicators('900', ' ', 1);
514    
515    Any indicator value other than C<0-9> will be treated as undefined.
516    
517    =cut
518    
519    sub marc_indicators {
520            my $f = shift || die "marc_indicators need field!\n";
521            my ($i1,$i2) = @_;
522            die "marc_indicators($f, ...) need i1!\n" unless(defined($i1));
523            die "marc_indicators($f, $i1, ...) need i2!\n" unless(defined($i2));
524    
525            $i1 = ' ' if ($i1 !~ /^\d$/);
526            $i2 = ' ' if ($i2 !~ /^\d$/);
527            @{ $marc_indicators->{$f} } = ($i1,$i2);
528    }
529    
530    =head2 marc_compose
531    
532    Save values for each MARC subfield explicitly
533    
534      marc_compose('900',
535            'a', rec('200','a')
536            'b', rec('201','a')
537            'a', rec('200','b')
538            'c', rec('200','c')
539      );
540    
541    If you specify C<+> for subfield, value will be appended
542    to previous defined subfield.
543    
544    =cut
545    
546    sub marc_compose {
547            my $f = shift or die "marc_compose needs field";
548            die "marc_compose field must be numer" unless ($f =~ /^\d+$/);
549    
550            my ($i1,$i2) = defined($marc_indicators->{$f}) ? @{ $marc_indicators->{$f} } : (' ',' ');
551            my $m = [ $f, $i1, $i2 ];
552    
553            warn "### marc_compose input subfields = ", dump(@_),$/ if ($debug > 2);
554    
555          if ($eval_code) {          if ($#_ % 2 != 1) {
556                  my $eval = $self->fill_in($rec,$eval_code,$i) || return;                  die "ERROR: marc_compose",dump($f,@_)," not valid (must be even).\nDo you need to add first() or join() around some argument?\n";
                 $log->debug("about to eval{$eval} format: $out");  
                 return if (! $self->_eval($eval));  
557          }          }
558            
559          if ($filter_name) {          while (@_) {
560                  my @filter_args;                  my $sf = shift;
561                  if ($filter_name =~ s/(\w+)\((.*)\)/$1/) {                  my $v = shift;
562                          @filter_args = split(/,/, $2);  
563                  }                  next unless (defined($v) && $v !~ /^\s*$/);
564                  if ($self->{'filter'}->{$filter_name}) {                  warn "## ++ marc_compose($f,$sf,$v) ", dump( $m ),$/ if ($debug > 1);
565                          $log->debug("about to filter{$filter_name} format: $out with arguments: ", join(",", @filter_args));                  if ($sf ne '+') {
566                          unshift @filter_args, $out;                          push @$m, ( $sf, $v );
567                          $out = $self->{'filter'}->{$filter_name}->(@filter_args);                  } else {
568                          return unless(defined($out));                          $m->[ $#$m ] .= $v;
                         $log->debug("filter result: $out");  
                 } elsif (! $warn_once->{$filter_name}) {  
                         $log->warn("trying to use undefined filter $filter_name");  
                         $warn_once->{$filter_name}++;  
569                  }                  }
570          }          }
571    
572          return $out;          warn "## marc_compose current marc = ", dump( $m ),$/ if ($debug > 1);
573    
574            push @{ $marc_record->[ $marc_record_offset ] }, $m if ($#{$m} > 2);
575  }  }
576    
577  =head2 parse_to_arr  =head2 marc_duplicate
578    
579    Generate copy of current MARC record and continue working on copy
580    
581  Similar to C<parse>, but returns array of all repeatable fields    marc_duplicate();
582    
583   my @arr = $webpac->parse_to_arr($rec,'v250^a');  Copies can be accessed using C<< _get_marc_fields( fetch_next => 1 ) >> or
584    C<< _get_marc_fields( offset => 42 ) >>.
585    
586  =cut  =cut
587    
588  sub parse_to_arr {  sub marc_duplicate {
589          my $self = shift;           my $m = $marc_record->[ -1 ];
590             die "can't duplicate record which isn't defined" unless ($m);
591             push @{ $marc_record }, dclone( $m );
592             warn "## marc_duplicate = ", dump(@$marc_record), $/ if ($debug > 1);
593             $marc_record_offset = $#{ $marc_record };
594             warn "## marc_record_offset = $marc_record_offset", $/ if ($debug > 1);
595    }
596    
597          my ($rec, $format_utf8) = @_;  =head2 marc_remove
598    
599          my $log = $self->_get_logger();  Remove some field or subfield from MARC record.
600    
601          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);    marc_remove('200');
602          return if (! $format_utf8);    marc_remove('200','a');
603    
604          my $i = 0;  This will erase field C<200> or C<200^a> from current MARC record.
605          my @arr;  
606    This is useful after calling C<marc_duplicate> or on it's own (but, you
607    should probably just remove that subfield definition if you are not
608    using C<marc_duplicate>).
609    
610    FIXME: support fields < 10.
611    
612    =cut
613    
614    sub marc_remove {
615            my ($f, $sf) = @_;
616    
617            die "marc_remove needs record number" unless defined($f);
618    
619            my $marc = $marc_record->[ $marc_record_offset ];
620    
621          my $rec_size = { '_' => '_' };          warn "### marc_remove before = ", dump( $marc ), $/ if ($debug > 2);
622    
623          while (my $v = $self->parse($rec,$format_utf8,$i++,\$rec_size)) {          my $i = 0;
624                  push @arr, $v;          foreach ( 0 .. $#{ $marc } ) {
625                  warn "parse rec_size = ", Dumper($rec_size);                  last unless (defined $marc->[$i]);
626                    warn "#### working on ",dump( @{ $marc->[$i] }), $/ if ($debug > 3);
627                    if ($marc->[$i]->[0] eq $f) {
628                            if (! defined $sf) {
629                                    # remove whole field
630                                    splice @$marc, $i, 1;
631                                    warn "#### slice \@\$marc, $i, 1 = ",dump( @{ $marc }), $/ if ($debug > 3);
632                                    $i--;
633                            } else {
634                                    foreach my $j ( 0 .. (( $#{ $marc->[$i] } - 3 ) / 2) ) {
635                                            my $o = ($j * 2) + 3;
636                                            if ($marc->[$i]->[$o] eq $sf) {
637                                                    # remove subfield
638                                                    splice @{$marc->[$i]}, $o, 2;
639                                                    warn "#### slice \@{\$marc->[$i]}, $o, 2 = ", dump( @{ $marc }), $/ if ($debug > 3);
640                                                    # is record now empty?
641                                                    if ($#{ $marc->[$i] } == 2) {
642                                                            splice @$marc, $i, 1;
643                                                            warn "#### slice \@\$marc, $i, 1 = ", dump( @{ $marc }), $/ if ($debug > 3);
644                                                            $i--;
645                                                    };
646                                            }
647                                    }
648                            }
649                    }
650                    $i++;
651          }          }
652    
653          $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);          warn "### marc_remove($f", $sf ? ",$sf" : "", ") after = ", dump( $marc ), $/ if ($debug > 2);
654    
655            $marc_record->[ $marc_record_offset ] = $marc;
656    
657          return @arr;          warn "## full marc_record = ", dump( @{ $marc_record }), $/ if ($debug > 1);
658  }  }
659    
660    =head2 marc_original_order
661    
662  =head2 fill_in  Copy all subfields preserving original order to marc field.
663    
664  Workhourse of all: takes record from in-memory structure of database and    marc_original_order( marc_field_number, original_input_field_number );
 strings with placeholders and returns string or array of with substituted  
 values from record.  
665    
666   my $text = $webpac->fill_in($rec,'v250^a');  Please note that field numbers are consistent with other commands (marc
667    field number first), but somewhat counter-intuitive (destination and then
668    source).
669    
670  Optional argument is ordinal number for repeatable fields. By default,  You might want to use this command if you are just renaming subfields or
671  it's assume to be first repeatable field (fields are perl array, so first  using pre-processing modify_record in C<config.yml> and don't need any
672  element is 0).  post-processing or want to preserve order of original subfields.
 Following example will read second value from repeatable field.  
673    
  my $text = $webpac->fill_in($rec,'Title: v250^a',1);  
674    
675  This function B<does not> perform parsing of format to inteligenty skip  =cut
 delimiters before fields which aren't used.  
676    
677  This method will automatically decode UTF-8 string to local code page  sub marc_original_order {
 if needed.  
678    
679  There is optional parametar C<$record_size> which can be used to get sizes of          my ($to, $from) = @_;
680  all C<field^subfield> combinations in this format.          die "marc_original_order needs from and to fields\n" unless ($from && $to);
681    
682   my $text = $webpac->fill_in($rec,'got: v900^a v900^x',0,\$rec_size);          return unless defined($rec->{$from});
683    
684  =cut          my $r = $rec->{$from};
685            die "record field $from isn't array\n" unless (ref($r) eq 'ARRAY');
686    
687  sub fill_in {          my ($i1,$i2) = defined($marc_indicators->{$to}) ? @{ $marc_indicators->{$to} } : (' ',' ');
688          my $self = shift;          warn "## marc_original_order($to,$from) source = ", dump( $r ),$/ if ($debug > 1);
689    
690          my $log = $self->_get_logger();          foreach my $d (@$r) {
691    
692          my ($rec,$format,$i,$rec_size) = @_;                  if (! defined($d->{subfields}) && ref($d->{subfields}) ne 'ARRAY') {
693                            warn "# marc_original_order($to,$from): field $from doesn't have subfields specification\n";
694                            next;
695                    }
696            
697                    my @sfs = @{ $d->{subfields} };
698    
699                    die "field $from doesn't have even number of subfields specifications\n" unless($#sfs % 2 == 1);
700    
701                    warn "#--> d: ",dump($d), "\n#--> sfs: ",dump(@sfs),$/ if ($debug > 2);
702    
703          $log->logconfess("need data record") unless ($rec);                  my $m = [ $to, $i1, $i2 ];
         $log->logconfess("need format to parse") unless($format);  
704    
705          # iteration (for repeatable fields)                  while (my $sf = shift @sfs) {
         $i ||= 0;  
706    
707          $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999));                          warn "#--> sf: ",dump($sf), $/ if ($debug > 2);
708                            my $offset = shift @sfs;
709                            die "corrupted sufields specification for field $from\n" unless defined($offset);
710    
711          # FIXME remove for speedup?                          my $v;
712          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);                          if (ref($d->{$sf}) eq 'ARRAY') {
713                                    $v = $d->{$sf}->[$offset] if (defined($d->{$sf}->[$offset]));
714                            } elsif ($offset == 0) {
715                                    $v = $d->{$sf};
716                            } else {
717                                    die "field $from subfield '$sf' need occurence $offset which doesn't exist", dump($d->{$sf});
718                            }
719                            push @$m, ( $sf, $v ) if (defined($v));
720                    }
721    
722          if (utf8::is_utf8($format)) {                  if ($#{$m} > 2) {
723                  $format = $self->_x($format);                          push @{ $marc_record->[ $marc_record_offset ] }, $m;
724                    }
725          }          }
726    
727          my $found = 0;          warn "## marc_record = ", dump( $marc_record ),$/ if ($debug > 1);
728          my $just_single = 1;  }
729    
         my $eval_code;  
         # remove eval{...} from beginning  
         $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);  
730    
731          my $filter_name;  =head1 Functions to extract data from input
         # remove filter{...} from beginning  
         $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);  
732    
733          # do actual replacement of placeholders  This function should be used inside functions to create C<data_structure> described
734          # repeatable fields  above.
         if ($format =~ s/v(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,$i,\$found,$rec_size)/ges) {  
                 $just_single = 0;  
         }  
735    
736          # non-repeatable fields  =head2 _pack_subfields_hash
         if ($format =~ s/s(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,0,\$found,$rec_size)/ges) {  
                 return if ($i > 0 && $just_single);  
         }  
737    
738          if ($found) {   @subfields = _pack_subfields_hash( $h );
739                  $log->debug("format: $format");   $subfields = _pack_subfields_hash( $h, 1 );
740                  if ($eval_code) {  
741                          my $eval = $self->fill_in($rec,$eval_code,$i);  Return each subfield value in array or pack them all together and return scalar
742                          return if (! $self->_eval($eval));  with subfields (denoted by C<^>) and values.
743                  }  
744                  if ($filter_name && $self->{'filter'}->{$filter_name}) {  =cut
745                          $log->debug("filter '$filter_name' for $format");  
746                          $format = $self->{'filter'}->{$filter_name}->($format);  sub _pack_subfields_hash {
747                          return unless(defined($format));  
748                          $log->debug("filter result: $format");          warn "## _pack_subfields_hash( ",dump(@_), " )\n" if ($debug > 1);
749                  }  
750                  # do we have lookups?          my ($h,$include_subfields) = @_;
751                  if ($self->{'lookup'}) {  
752                          if ($self->{'lookup'}->can('lookup')) {          if ( defined($h->{subfields}) ) {
753                                  my @lookup = $self->{lookup}->lookup($format);                  my $sfs = delete $h->{subfields} || die "no subfields?";
754                                  $log->debug("lookup $format", join(", ", @lookup));                  my @out;
755                                  return @lookup;                  while (@$sfs) {
756                            my $sf = shift @$sfs;
757                            push @out, '^' . $sf if ($include_subfields);
758                            my $o = shift @$sfs;
759                            if ($o == 0 && ref( $h->{$sf} ) ne 'ARRAY' ) {
760                                    # single element subfields are not arrays
761    #warn "====> $sf $o / $#$sfs ", dump( $sfs, $h->{$sf} ), "\n";
762    
763                                    push @out, $h->{$sf};
764                          } else {                          } else {
765                                  $log->warn("Have lookup object but can't invoke lookup method");  #warn "====> $sf $o / $#$sfs ", dump( $sfs, $h->{$sf} ), "\n";
766                                    push @out, $h->{$sf}->[$o];
767                          }                          }
768                    }
769                    if ($include_subfields) {
770                            return join('', @out);
771                  } else {                  } else {
772                          return $format;                          return @out;
773                  }                  }
774          } else {          } else {
775                  return;                  if ($include_subfields) {
776                            my $out = '';
777                            foreach my $sf (sort keys %$h) {
778                                    if (ref($h->{$sf}) eq 'ARRAY') {
779                                            $out .= '^' . $sf . join('^' . $sf, @{ $h->{$sf} });
780                                    } else {
781                                            $out .= '^' . $sf . $h->{$sf};
782                                    }
783                            }
784                            return $out;
785                    } else {
786                            # FIXME this should probably be in alphabetical order instead of hash order
787                            values %{$h};
788                    }
789          }          }
790  }  }
791    
792    =head2 rec1
793    
794  =head2 fill_in_to_arr  Return all values in some field
795    
796  Similar to C<fill_in>, but returns array of all repeatable fields. Usable    @v = rec1('200')
 for fields which have lookups, so they shouldn't be parsed but rather  
 C<fill_id>ed.  
797    
798   my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]');  TODO: order of values is probably same as in source data, need to investigate that
799    
800  =cut  =cut
801    
802  sub fill_in_to_arr {  sub rec1 {
803          my $self = shift;          my $f = shift;
804            warn "rec1($f) = ", dump( $rec->{$f} ), $/ if ($debug > 1);
805            return unless (defined($rec) && defined($rec->{$f}));
806            warn "rec1($f) = ", dump( $rec->{$f} ), $/ if ($debug > 1);
807            if (ref($rec->{$f}) eq 'ARRAY') {
808                    my @out;
809                    foreach my $h ( @{ $rec->{$f} } ) {
810                            if (ref($h) eq 'HASH') {
811                                    push @out, ( _pack_subfields_hash( $h ) );
812                            } else {
813                                    push @out, $h;
814                            }
815                    }
816                    return @out;
817            } elsif( defined($rec->{$f}) ) {
818                    return $rec->{$f};
819            }
820    }
821    
822    =head2 rec2
823    
824          my ($rec, $format_utf8) = @_;  Return all values in specific field and subfield
825    
826          my $log = $self->_get_logger();    @v = rec2('200','a')
827    
828          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  =cut
         return if (! $format_utf8);  
829    
830          my $i = 0;  sub rec2 {
831          my @arr;          my $f = shift;
832            return unless (defined($rec && $rec->{$f}));
833            my $sf = shift;
834            warn "rec2($f,$sf) = ", dump( $rec->{$f} ), $/ if ($debug > 1);
835            return map {
836                    if (ref($_->{$sf}) eq 'ARRAY') {
837                            @{ $_->{$sf} };
838                    } else {
839                            $_->{$sf};
840                    }
841            } grep { ref($_) eq 'HASH' && $_->{$sf} } @{ $rec->{$f} };
842    }
843    
844          my $rec_size;  =head2 rec
845    
846          while (my $v = $self->fill_in($rec,$format_utf8,$i,\$rec_size)) {  syntaxtic sugar for
847                  push @arr, $v;  
848                  warn "rec_size = ", Dumper($rec_size);    @v = rec('200')
849          }    @v = rec('200','a')
850    
851          $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  =cut
852    
853          return @arr;  sub rec {
854            my @out;
855            if ($#_ == 0) {
856                    @out = rec1(@_);
857            } elsif ($#_ == 1) {
858                    @out = rec2(@_);
859            }
860            if (@out) {
861                    return @out;
862            } else {
863                    return '';
864            }
865  }  }
866    
867    =head2 regex
868    
869    Apply regex to some or all values
870    
871  =head2 get_data    @v = regex( 's/foo/bar/g', @v );
872    
873    =cut
874    
875    sub regex {
876            my $r = shift;
877            my @out;
878            #warn "r: $r\n", dump(\@_);
879            foreach my $t (@_) {
880                    next unless ($t);
881                    eval "\$t =~ $r";
882                    push @out, $t if ($t && $t ne '');
883            }
884            return @out;
885    }
886    
887  Returns value from record.  =head2 prefix
888    
889   my $text = $self->get_data(\$rec,$f,$sf,$i,\$found,\$rec_size);  Prefix all values with a string
890    
891  Required arguments are:    @v = prefix( 'my_', @v );
892    
893  =over 8  =cut
894    
895  =item C<$rec>  sub prefix {
896            my $p = shift or return;
897            return map { $p . $_ } grep { defined($_) } @_;
898    }
899    
900  record reference  =head2 suffix
901    
902  =item C<$f>  suffix all values with a string
903    
904  field    @v = suffix( '_my', @v );
905    
906  =item C<$sf>  =cut
907    
908  optional subfield  sub suffix {
909            my $s = shift or die "suffix needs string as first argument";
910            return map { $_ . $s } grep { defined($_) } @_;
911    }
912    
913  =item C<$i>  =head2 surround
914    
915  index offset for repeatable values ( 0 ... $rec_size->{'400^a'} )  surround all values with a two strings
916    
917  =item C<$found>    @v = surround( 'prefix_', '_suffix', @v );
918    
919  optional variable that will be incremeted if preset  =cut
920    
921  =item C<$rec_size>  sub surround {
922            my $p = shift or die "surround need prefix as first argument";
923            my $s = shift or die "surround needs suffix as second argument";
924            return map { $p . $_ . $s } grep { defined($_) } @_;
925    }
926    
927  hash to hold maximum occurances of C<field^subfield> combinations  =head2 first
 (which can be accessed using keys in same format)  
928    
929  =back  Return first element
930    
931  Returns value or empty string, updates C<$found> and C<rec_size>    $v = first( @v );
 if present.  
932    
933  =cut  =cut
934    
935  sub get_data {  sub first {
936          my $self = shift;          my $r = shift;
937            return $r;
938    }
939    
940          my ($rec,$f,$sf,$i,$found,$cache) = @_;  =head2 lookup
941    
942          return '' unless ($$rec->{$f} && ref($$rec->{$f}) eq 'ARRAY');  Consult lookup hashes for some value
943    
944          if (defined($$cache)) {    @v = lookup( $v );
945                  $$cache->{ $f . ( $sf ? '^' . $sf : '' ) } ||= scalar @{ $$rec->{$f} };    @v = lookup( @v );
         }  
946    
947          return '' unless ($$rec->{$f}->[$i]);  FIXME B<currently this one is broken!>
948    
949          {  =cut
950                  no strict 'refs';  
951                  if (defined($sf)) {  sub lookup {
952                          $$found++ if (defined($$found) && $$rec->{$f}->[$i]->{$sf});          my $k = shift or return;
953                          return $$rec->{$f}->[$i]->{$sf};          return unless (defined($lookup->{$k}));
954                  } else {          if (ref($lookup->{$k}) eq 'ARRAY') {
955                          $$found++ if (defined($$found));                  return @{ $lookup->{$k} };
956                          # it still might have subfields, just          } else {
957                          # not specified, so we'll dump some debug info                  return $lookup->{$k};
                         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];  
                         }  
                 }  
958          }          }
959  }  }
960    
961    =head2 save_into_lookup
962    
963  =head2 apply_format  Save value into lookup.
   
 Apply format specified in tag with C<format_name="name"> and  
 C<format_delimiter=";;">.  
964    
965   my $text = $webpac->apply_format($format_name,$format_delimiter,$data);    save_into_lookup($database,$input,$key,sub {
966            # code which produce one or more values
967      });
968    
969  Formats can contain C<lookup{...}> if you need them.  This function shouldn't be called directly, it's called from code created by L<WebPAC::Parser>.
970    
971  =cut  =cut
972    
973  sub apply_format {  sub save_into_lookup {
974          my $self = shift;          my ($database,$input,$key,$coderef) = @_;
975            die "save_into_lookup needs database" unless defined($database);
976          my ($name,$delimiter,$data) = @_;          die "save_into_lookup needs input" unless defined($input);
977            die "save_into_lookup needs key" unless defined($key);
978            die "save_into_lookup needs CODE" unless ( defined($coderef) && ref($coderef) eq 'CODE' );
979            my $mfn = $rec->{'000'}->[0] || die "mfn not defined or zero";
980            foreach my $v ( $coderef->() ) {
981                    $lookup->{$database}->{$input}->{$key}->{$v}->{$mfn}++;
982                    warn "# saved lookup $database/$input/$key [$v] $mfn\n"; #if ($debug > 1);
983            }
984    }
985    
986          my $log = $self->_get_logger();  =head2 config
987    
988          if (! $self->{'import_xml'}->{'format'}->{$name}) {  Consult config values stored in C<config.yml>
                 $log->warn("<format name=\"$name\"> is not defined in ",$self->{'import_xml_file'});  
                 return $data;  
         }  
989    
990          $log->warn("no delimiter for format $name") if (! $delimiter);    # return database code (key under databases in yaml)
991      $database_code = config();    # use _ from hash
992      $database_name = config('name');
993      $database_input_name = config('input name');
994      $tag = config('input normalize tag');
995    
996          my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'");  Up to three levels are supported.
997    
998          my @data = split(/\Q$delimiter\E/, $data);  =cut
999    
1000          my $out = sprintf($format, @data);  sub config {
1001          $log->debug("using format $name [$format] on $data to produce: $out");          return unless ($config);
1002    
1003          if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) {          my $p = shift;
                 return $self->{'lookup'}->lookup($out);  
         } else {  
                 return $out;  
         }  
1004    
1005  }          $p ||= '';
1006    
1007  =head2 sort_arr          my $v;
1008    
1009  Sort array ignoring case and html in data          warn "### getting config($p)\n" if ($debug > 1);
1010    
1011   my @sorted = $webpac->sort_arr(@unsorted);          my @p = split(/\s+/,$p);
1012            if ($#p < 0) {
1013                    $v = $config->{ '_' };  # special, database code
1014            } else {
1015    
1016  =cut                  my $c = dclone( $config );
1017    
1018  sub sort_arr {                  foreach my $k (@p) {
1019          my $self = shift;                          warn "### k: $k c = ",dump($c),$/ if ($debug > 1);
1020                            if (ref($c) eq 'ARRAY') {
1021                                    $c = shift @$c;
1022                                    warn "config($p) taking first occurence of '$k', probably not what you wanted!\n";
1023                                    last;
1024                            }
1025    
1026          my $log = $self->_get_logger();                          if (! defined($c->{$k}) ) {
1027                                    $c = undef;
1028                                    last;
1029                            } else {
1030                                    $c = $c->{$k};
1031                            }
1032                    }
1033                    $v = $c if ($c);
1034    
1035          # FIXME add Schwartzian Transformation?          }
1036    
1037          my @sorted = sort {          warn "## config( '$p' ) = ",dump( $v ),$/ if ($v && $debug);
1038                  $a =~ s#<[^>]+/*>##;          warn "config( '$p' ) is empty\n" if (! $v);
                 $b =~ s#<[^>]+/*>##;  
                 lc($b) cmp lc($a)  
         } @_;  
         $log->debug("sorted values: ",sub { join(", ",@sorted) });  
1039    
1040          return @sorted;          return $v;
1041  }  }
1042    
1043    =head2 id
1044    
1045  =head1 INTERNAL METHODS  Returns unique id of this record
1046    
1047  =head2 _sort_by_order    $id = id();
1048    
1049  Sort xml tags data structure accoding to C<order=""> attribute.  Returns C<42/2> for 2nd occurence of MFN 42.
1050    
1051  =cut  =cut
1052    
1053  sub _sort_by_order {  sub id {
1054          my $self = shift;          my $mfn = $config->{_mfn} || die "no _mfn in config data";
1055            return $mfn . $#{$marc_record} ? $#{$marc_record} + 1 : '';
         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;  
1056  }  }
1057    
1058  =head2 _x  =head2 join_with
   
 Convert strings from C<conf/normalize/*.xml> encoding into application  
 specific encoding (optinally specified using C<code_page> to C<new>  
 constructor).  
1059    
1060   my $text = $n->_x('normalize text string');  Joins walues with some delimiter
1061    
1062  This is a stub so that other modules doesn't have to implement it.    $v = join_with(", ", @v);
1063    
1064  =cut  =cut
1065    
1066  sub _x {  sub join_with {
1067          my $self = shift;          my $d = shift;
1068          return shift;          warn "### join_with('$d',",dump(@_),")\n" if ($debug > 2);
1069            my $v = join($d, grep { defined($_) && $_ ne '' } @_);
1070            return '' unless defined($v);
1071            return $v;
1072  }  }
1073    
1074    =head2 split_rec_on
1075    
1076  =head1 AUTHOR  Split record subfield on some regex and take one of parts out
1077    
1078  Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>    $a_before_semi_column =
1079            split_rec_on('200','a', /\s*;\s*/, $part);
1080    
1081  =head1 COPYRIGHT & LICENSE  C<$part> is optional number of element. First element is
1082    B<1>, not 0!
1083    
1084  Copyright 2005 Dobrica Pavlinusic, All Rights Reserved.  If there is no C<$part> parameter or C<$part> is 0, this function will
1085    return all values produced by splitting.
 This program is free software; you can redistribute it and/or modify it  
 under the same terms as Perl itself.  
1086    
1087  =cut  =cut
1088    
1089  1; # End of WebPAC::Normalize  sub split_rec_on {
1090            die "split_rec_on need (fld,sf,regex[,part]" if ($#_ < 2);
1091    
1092            my ($fld, $sf, $regex, $part) = @_;
1093            warn "### regex ", ref($regex), $regex, $/ if ($debug > 2);
1094    
1095            my @r = rec( $fld, $sf );
1096            my $v = shift @r;
1097            warn "### first rec($fld,$sf) = ",dump($v),$/ if ($debug > 2);
1098    
1099            return '' if ( ! defined($v) || $v =~ /^\s*$/);
1100    
1101            my @s = split( $regex, $v );
1102            warn "## split_rec_on($fld,$sf,$regex,$part) = ",dump(@s),$/ if ($debug > 1);
1103            if ($part && $part > 0) {
1104                    return $s[ $part - 1 ];
1105            } else {
1106                    return @s;
1107            }
1108    }
1109    
1110    # END
1111    1;

Legend:
Removed from v.371  
changed lines
  Added in v.712

  ViewVC Help
Powered by ViewVC 1.1.26