/[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 268 by dpavlin, Fri Dec 16 21:09:42 2005 UTC revision 550 by dpavlin, Fri Jun 30 18:48:33 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    
7            tag search display
8            marc marc_indicators marc_repeatable_subfield
9    
10            rec1 rec2 rec
11            regex prefix suffix surround
12            first lookup join_with
13    /;
14    
15  use warnings;  use warnings;
16  use strict;  use strict;
17  use base 'WebPAC::Common';  
18  use Data::Dumper;  #use base qw/WebPAC::Common/;
19    use Data::Dump qw/dump/;
20    use Encode qw/from_to/;
21    
22    # debugging warn(s)
23    my $debug = 0;
24    
25    
26  =head1 NAME  =head1 NAME
27    
28  WebPAC::Normalize - data mungling for normalisation  WebPAC::Normalize - describe normalisaton rules using sets
29    
30  =head1 VERSION  =head1 VERSION
31    
# Line 19  our $VERSION = '0.06'; Line 37  our $VERSION = '0.06';
37    
38  =head1 SYNOPSIS  =head1 SYNOPSIS
39    
40  This package contains code that mungle data to produce normalized format.  This module uses C<conf/normalize/*.pl> files to perform normalisation
41    from input records using perl functions which are specialized for set
42    processing.
43    
44    Sets are implemented as arrays, and normalisation file is valid perl, which
45    means that you check it's validity before running WebPAC using
46    C<perl -c normalize.pl>.
47    
48    Normalisation can generate multiple output normalized data. For now, supported output
49    types (on the left side of definition) are: C<tag>, C<display>, C<search> and
50    C<marc>.
51    
52  It contains several assumptions:  =head1 FUNCTIONS
53    
54  =over  Functions which start with C<_> are private and used by WebPAC internally.
55    All other functions are available for use within normalisation rules.
56    
57  =item *  =head2 data_structure
58    
59  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.  
60    
61  =item *    my $ds = WebPAC::Normalize::data_structure(
62            lookup => $lookup->lookup_hash,
63            row => $row,
64            rules => $normalize_pl_config,
65            marc_encoding => 'utf-8',
66      );
67    
68  source data records (C<$rec>) have unique identifiers in field C<000>  Options C<lookup>, C<row>, C<rules> and C<log> are mandatory while all
69    other are optional.
70    
71  =item *  This function will B<die> if normalizastion can't be evaled.
72    
73  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
74  perl code that is evaluated before producing output (value of field will be  C<WebPAC::Normalize::data_structure>.
 interpolated before that)  
75    
76  =item *  =cut
77    
78  optional C<filter{filter_name}> at B<begining of format> will apply perl  sub data_structure {
79  code defined as code ref on format after field substitution to producing          my $arg = {@_};
 output  
80    
81  There is one built-in filter called C<regex> which can be use like this:          die "need row argument" unless ($arg->{row});
82            die "need normalisation argument" unless ($arg->{rules});
83    
84    filter{regex(s/foo/bar/)}          no strict 'subs';
85            _set_lookup( $arg->{lookup} );
86            _set_rec( $arg->{row} );
87            _clean_ds( %{ $arg } );
88            eval "$arg->{rules}";
89            die "error evaling $arg->{rules}: $@\n" if ($@);
90    
91  =item *          return _get_ds();
92    }
93    
94  optional C<lookup{...}> will be then performed. See C<WebPAC::Lookups>.  =head2 _set_rec
95    
96  =item *  Set current record hash
97    
98  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.  
99    
100  =back  =cut
101    
102  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.  
103    
104    sub _set_rec {
105            $rec = shift or die "no record hash";
106    }
107    
108    =head2 _get_ds
109    
110    Return hash formatted as data structure
111    
112  =head1 FUNCTIONS    my $ds = _get_ds();
113    
114  =head2 new  =cut
115    
116  Create new normalisation object  my ($out,$marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators);
117    
118    my $n = new WebPAC::Normalize::Something(  sub _get_ds {
119          filter => {          return $out;
120                  'filter_name_1' => sub {  }
                         # filter code  
                         return length($_);  
                 }, ...  
         },  
         db => $db_obj,  
         lookup_regex => $lookup->regex,  
         lookup => $lookup_obj,  
         prefix => 'foobar',  
   );  
121    
122  Parametar C<filter> defines user supplied snippets of perl code which can  =head2 _clean_ds
 be use with C<filter{...}> notation.  
123    
124  C<prefix> is used to form filename for database record (to support multiple  Clean data structure hash for next record
 source files which are joined in one database).  
125    
126  Recommended parametar C<lookup_regex> is used to enable parsing of lookups    _clean_ds();
 in structures. If you pass this parametar, you must also pass C<lookup>  
 which is C<WebPAC::Lookup> object.  
127    
128  =cut  =cut
129    
130  sub new {  sub _clean_ds {
131          my $class = shift;          my $a = {@_};
132          my $self = {@_};          ($out,$marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators) = ();
133          bless($self, $class);          $marc_encoding = $a->{marc_encoding};
134    }
         my $r = $self->{'lookup_regex'} ? 1 : 0;  
         my $l = $self->{'lookup'} ? 1 : 0;  
   
         my $log = $self->_get_logger();  
135    
136          # those two must be in pair  =head2 _set_lookup
         if ( ($r & $l) != ($r || $l) ) {  
                 my $log = $self->_get_logger();  
                 $log->logdie("lookup_regex and lookup must be in pair");  
         }  
137    
138          $log->logdie("lookup must be WebPAC::Lookup object") if ($self->{'lookup'} && ! $self->{'lookup'}->isa('WebPAC::Lookup'));  Set current lookup hash
139    
140          $log->warn("no prefix defined. please check that!") unless ($self->{'prefix'});    _set_lookup( $lookup );
141    
142          $log->debug("using lookup regex: ", $self->{lookup_regex}) if ($r && $l);  =cut
143    
144          if ($self->{filter} && ! $self->{filter}->{regex}) {  my $lookup;
                 $log->debug("adding built-in filter regex");  
                 $self->{filter}->{regex} = sub {  
                         my ($val, $regex) = @_;  
                         eval "\$val =~ $regex";  
                         return $val;  
                 };  
         }  
145    
146          $self ? return $self : return undef;  sub _set_lookup {
147            $lookup = shift;
148  }  }
149    
150    =head2 _get_marc_fields
151    
152  =head2 data_structure  Get all fields defined by calls to C<marc>
153    
154  Create in-memory data structure which represents normalized layout from          $marc->add_fields( WebPAC::Normalize:_get_marc_fields() );
 C<conf/normalize/*.xml>.  
155    
 This structures are used to produce output.  
156    
  my $ds = $webpac->data_structure($rec);  
157    
158  =cut  We are using I<magic> which detect repeatable fields only from
159    sequence of field/subfield data generated by normalization.
160    
161  sub data_structure {  Repeatable field is created if there is second occurence of same subfield or
162          my $self = shift;  if any of indicators are different. This is sane for most cases except for
163    non-repeatable fields with repeatable subfields.
164    
165          my $log = $self->_get_logger();  You can change behaviour of that using C<marc_repeatable_subfield>.
166    
167          my $rec = shift;  =cut
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
168    
169          $log->debug("data_structure rec = ", sub { Dumper($rec) });  sub _get_marc_fields {
170    
         $log->logdie("need unique ID (mfn) in field 000 of record ", sub { Dumper($rec) } ) unless (defined($rec->{'000'}));  
171    
172          my $id = $rec->{'000'}->[0] || $log->logdie("field 000 isn't array!");          # first, sort all existing fields
173            # XXX might not be needed, but modern perl might randomize elements in hash
174            my @sorted_marc_record = sort {
175                    $a->[0] . $a->[3] cmp $b->[0] . $b->[3]
176            } @{ $marc_record };
177    
178          my $cache_file;          # output marc fields
179            my @m;
180    
181          if ($self->{'db'}) {          # count unique field-subfields (used for offset when walking to next subfield)
182                  my $ds = $self->{'db'}->load_ds( id => $id, prefix => $self->{prefix} );          my $u;
183                  $log->debug("load_ds( rec = ", sub { Dumper($rec) }, ") = ", sub { Dumper($ds) });          map { $u->{ $_->[0] . $_->[3]  }++ } @sorted_marc_record;
                 return $ds if ($ds);  
                 $log->debug("cache miss, creating");  
         }  
184    
185          my @sorted_tags;          if ($debug) {
186          if ($self->{tags_by_order}) {                  warn "## marc_repeatable_subfield ", dump( $marc_repeatable_subfield ), $/;
187                  @sorted_tags = @{$self->{tags_by_order}};                  warn "## marc_record ", dump( $marc_record ), $/;
188          } else {                  warn "## sorted_marc_record ", dump( \@sorted_marc_record ), $/;
189                  @sorted_tags = sort { $self->_sort_by_order } keys %{$self->{'import_xml'}->{'indexer'}};                  warn "## subfield count ", dump( $u ), $/;
                 $self->{tags_by_order} = \@sorted_tags;  
190          }          }
191    
192          my $ds;          my $len = $#sorted_marc_record;
193            my $visited;
194            my $i = 0;
195            my $field;
196    
197          $log->debug("tags: ",sub { join(", ",@sorted_tags) });          foreach ( 0 .. $len ) {
198    
199          foreach my $field (@sorted_tags) {                  # find next element which isn't visited
200                    while ($visited->{$i}) {
201                            $i = ($i + 1) % ($len + 1);
202                    }
203    
204                  my $row;                  # mark it visited
205                    $visited->{$i}++;
206    
207  #print "field $field [",$self->{'tag'},"] = ",Dumper($self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}});                  my $row = $sorted_marc_record[$i];
208    
209                  foreach my $tag (@{$self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}}) {                  # field and subfield which is key for
210                          my $format;                  # marc_repeatable_subfield and u
211                    my $fsf = $row->[0] . $row->[3];
212    
213                    if ($debug > 1) {
214    
215                            print "### field so far [", $#$field, "] : ", dump( $field ), " ", $field ? 'T' : 'F', $/;
216                            print "### this [$i]: ", dump( $row ),$/;
217                            print "### sf: ", $row->[3], " vs ", $field->[3],
218                                    $marc_repeatable_subfield->{ $row->[0] . $row->[3] } ? ' (repeatable)' : '', $/,
219                                    if ($#$field >= 0);
220    
221                          $log->logdie("expected tag HASH and got $tag") unless (ref($tag) eq 'HASH');                  }
                         $format = $tag->{'value'} || $tag->{'content'};  
222    
223                          $log->debug("format: $format");                  # if field exists
224                    if ( $#$field >= 0 ) {
225                            if (
226                                    $row->[0] ne $field->[0] ||             # field
227                                    $row->[1] ne $field->[1] ||             # i1
228                                    $row->[2] ne $field->[2]                # i2
229                            ) {
230                                    push @m, $field;
231                                    warn "## saved/1 ", dump( $field ),$/ if ($debug);
232                                    $field = $row;
233    
234                            } elsif (
235                                    ( $row->[3] lt $field->[-2] )           # subfield which is not next (e.g. a after c)
236                                    ||
237                                    ( $row->[3] eq $field->[-2] &&          # same subfield, but not repeatable
238                                            ! $marc_repeatable_subfield->{ $fsf }
239                                    )
240                            ) {
241                                    push @m, $field;
242                                    warn "## saved/2 ", dump( $field ),$/ if ($debug);
243                                    $field = $row;
244    
                         my @v;  
                         if ($self->{'lookup_regex'} && $format =~ $self->{'lookup_regex'}) {  
                                 @v = $self->fill_in_to_arr($rec,$format);  
245                          } else {                          } else {
246                                  @v = $self->parse_to_arr($rec,$format);                                  # append new subfields to existing field
247                          }                                  push @$field, ( $row->[3], $row->[4] );
                         next if (! @v);  
   
                         if ($tag->{'sort'}) {  
                                 @v = $self->sort_arr(@v);  
                         }  
   
                         # use format?  
                         if ($tag->{'format_name'}) {  
                                 @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v;  
                         }  
   
                         # delimiter will join repeatable fields  
                         if ($tag->{'delimiter'}) {  
                                 @v = ( join($tag->{'delimiter'}, @v) );  
                         }  
   
                         # 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("type: $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;  
                                 }  
248                          }                          }
249                    } else {
250                            # insert first field
251                            $field = $row;
252                  }                  }
253    
254                  if ($row) {                  if (! $marc_repeatable_subfield->{ $fsf }) {
255                          $row->{'tag'} = $field;                          # make step to next subfield
256                            $i = ($i + $u->{ $fsf } ) % ($len + 1);
                         # 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");  
                         }  
   
                         $ds->{$row_name} = $row;  
   
                         $log->debug("row $field: ",sub { Dumper($row) });  
257                  }                  }
   
258          }          }
259    
260          $self->{'db'}->save_ds(          if ($#$field >= 0) {
261                  id => $id,                  push @m, $field;
262                  ds => $ds,                  warn "## saved/3 ", dump( $field ),$/ if ($debug);
263                  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;  
264    
265            return @m;
266  }  }
267    
268  =head2 parse  =head1 Functions to create C<data_structure>
269    
270  Perform smart parsing of string, skipping delimiters for fields which aren't  Those functions generally have to first in your normalization file.
 defined. It can also eval code in format starting with C<eval{...}> and  
 return output or nothing depending on eval code.  
271    
272   my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i);  =head2 tag
273    
274  Filters are implemented here. While simple form of filters looks like this:  Define new tag for I<search> and I<display>.
275    
276    filter{name_of_filter}    tag('Title', rec('200','a') );
277    
 but, filters can also have variable number of parametars like this:  
   
   filter{name_of_filter(param,param,param)}  
278    
279  =cut  =cut
280    
281  my $warn_once;  sub tag {
282            my $name = shift or die "tag needs name as first argument";
283  sub parse {          my @o = grep { defined($_) && $_ ne '' } @_;
284          my $self = shift;          return unless (@o);
285            $out->{$name}->{tag} = $name;
286          my ($rec, $format_utf8, $i) = @_;          $out->{$name}->{search} = \@o;
287            $out->{$name}->{display} = \@o;
288          return if (! $format_utf8);  }
   
         my $log = $self->_get_logger();  
   
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
   
         $i = 0 if (! $i);  
289    
290          my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'});  =head2 display
291    
292          my @out;  Define tag just for I<display>
293    
294          $log->debug("format: $format");    @v = display('Title', rec('200','a') );
295    
296          my $eval_code;  =cut
         # remove eval{...} from beginning  
         $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);  
297    
298          my $filter_name;  sub display {
299          # remove filter{...} from beginning          my $name = shift or die "display needs name as first argument";
300          $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);          my @o = grep { defined($_) && $_ ne '' } @_;
301            return unless (@o);
302            $out->{$name}->{tag} = $name;
303            $out->{$name}->{display} = \@o;
304    }
305    
306          my $prefix;  =head2 search
         my $all_found=0;  
307    
308          while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) {  Prepare values just for I<search>
309    
310                  my $del = $1 || '';    @v = search('Title', rec('200','a') );
                 $prefix ||= $del if ($all_found == 0);  
311    
312                  # repeatable index  =cut
                 my $r = $i;  
                 $r = 0 if (lc("$2") eq 's');  
313    
314                  my $found = 0;  sub search {
315                  my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found);          my $name = shift or die "search needs name as first argument";
316            my @o = grep { defined($_) && $_ ne '' } @_;
317            return unless (@o);
318            $out->{$name}->{tag} = $name;
319            $out->{$name}->{search} = \@o;
320    }
321    
322                  if ($found) {  =head2 marc
                         push @out, $del;  
                         push @out, $tmp;  
                         $all_found += $found;  
                 }  
         }  
323    
324          return if (! $all_found);  Save value for MARC field
325    
326          my $out = join('',@out);    marc('900','a', rec('200','a') );
327    
328          if ($out) {  =cut
                 # add rest of format (suffix)  
                 $out .= $format;  
329    
330                  # add prefix if not there  sub marc {
331                  $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/);          my $f = shift or die "marc needs field";
332            die "marc field must be numer" unless ($f =~ /^\d+$/);
333    
334                  $log->debug("result: $out");          my $sf = shift or die "marc needs subfield";
         }  
335    
336          if ($eval_code) {          foreach (@_) {
337                  my $eval = $self->fill_in($rec,$eval_code,$i) || return;                  my $v = $_;             # make var read-write for Encode
338                  $log->debug("about to eval{$eval} format: $out");                  next unless (defined($v) && $v !~ /^\s*$/);
339                  return if (! $self->_eval($eval));                  from_to($v, 'iso-8859-2', $marc_encoding) if ($marc_encoding);
340                    my ($i1,$i2) = defined($marc_indicators->{$f}) ? @{ $marc_indicators->{$f} } : (' ',' ');
341                    push @{ $marc_record }, [ $f, $i1, $i2, $sf => $v ];
342          }          }
           
         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}++;  
                 }  
         }  
   
         return $out;  
343  }  }
344    
345  =head2 parse_to_arr  =head2 marc_repeatable_subfield
346    
347  Similar to C<parse>, but returns array of all repeatable fields  Save values for MARC repetable subfield
348    
349   my @arr = $webpac->parse_to_arr($rec,'v250^a');    marc_repeatable_subfield('910', 'z', rec('909') );
350    
351  =cut  =cut
352    
353  sub parse_to_arr {  sub marc_repeatable_subfield {
354          my $self = shift;          my ($f,$sf) = @_;
355            die "marc_repeatable_subfield need field and subfield!\n" unless ($f && $sf);
356            $marc_repeatable_subfield->{ $f . $sf }++;
357            marc(@_);
358    }
359    
360          my ($rec, $format_utf8) = @_;  =head2 marc_indicators
361    
362          my $log = $self->_get_logger();  Set both indicators for MARC field
363    
364          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);    marc_indicators('900', ' ', 1);
         return if (! $format_utf8);  
365    
366          my $i = 0;  Any indicator value other than C<0-9> will be treated as undefined.
         my @arr;  
367    
368          while (my $v = $self->parse($rec,$format_utf8,$i++)) {  =cut
                 push @arr, $v;  
         }  
369    
370          $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  sub marc_indicators {
371            my $f = shift || die "marc_indicators need field!\n";
372            my ($i1,$i2) = @_;
373            die "marc_indicators($f, ...) need i1!\n" unless(defined($i1));
374            die "marc_indicators($f, $i1, ...) need i2!\n" unless(defined($i2));
375    
376          return @arr;          $i1 = ' ' if ($i1 !~ /^\d$/);
377            $i2 = ' ' if ($i2 !~ /^\d$/);
378            @{ $marc_indicators->{$f} } = ($i1,$i2);
379  }  }
380    
381    
382  =head2 fill_in  =head1 Functions to extract data from input
383    
384  Workhourse of all: takes record from in-memory structure of database and  This function should be used inside functions to create C<data_structure> described
385  strings with placeholders and returns string or array of with substituted  above.
 values from record.  
386    
387   my $text = $webpac->fill_in($rec,'v250^a');  =head2 rec1
388    
389  Optional argument is ordinal number for repeatable fields. By default,  Return all values in some field
 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.  
390    
391   my $text = $webpac->fill_in($rec,'Title: v250^a',1);    @v = rec1('200')
392    
393  This function B<does not> perform parsing of format to inteligenty skip  TODO: order of values is probably same as in source data, need to investigate that
 delimiters before fields which aren't used.  
   
 This method will automatically decode UTF-8 string to local code page  
 if needed.  
394    
395  =cut  =cut
396    
397  sub fill_in {  sub rec1 {
398          my $self = shift;          my $f = shift;
399            return unless (defined($rec) && defined($rec->{$f}));
400          my $log = $self->_get_logger();          if (ref($rec->{$f}) eq 'ARRAY') {
401                    return map {
402          my $rec = shift || $log->logconfess("need data record");                          if (ref($_) eq 'HASH') {
403          my $format = shift || $log->logconfess("need format to parse");                                  values %{$_};
         # iteration (for repeatable fields)  
         my $i = shift || 0;  
   
         $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999));  
   
         # FIXME remove for speedup?  
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
   
         if (utf8::is_utf8($format)) {  
                 $format = $self->_x($format);  
         }  
   
         my $found = 0;  
   
         my $eval_code;  
         # remove eval{...} from beginning  
         $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);  
   
         my $filter_name;  
         # remove filter{...} from beginning  
         $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);  
   
         # do actual replacement of placeholders  
         # repeatable fields  
         $format =~ s/v(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,$i,\$found)/ges;  
         # non-repeatable fields  
         $format =~ s/s(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,0,\$found)/ges;  
   
         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;  
404                          } else {                          } else {
405                                  $log->warn("Have lookup object but can't invoke lookup method");                                  $_;
406                          }                          }
407                  } else {                  } @{ $rec->{$f} };
408                          return $format;          } elsif( defined($rec->{$f}) ) {
409                  }                  return $rec->{$f};
         } else {  
                 return;  
410          }          }
411  }  }
412    
413    =head2 rec2
414    
415  =head2 fill_in_to_arr  Return all values in specific field and subfield
   
 Similar to 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<fill_id>ed.  
416    
417   my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]');    @v = rec2('200','a')
418    
419  =cut  =cut
420    
421  sub fill_in_to_arr {  sub rec2 {
422          my $self = shift;          my $f = shift;
423            return unless (defined($rec && $rec->{$f}));
424            my $sf = shift;
425            return map { $_->{$sf} } grep { ref($_) eq 'HASH' && $_->{$sf} } @{ $rec->{$f} };
426    }
427    
428          my ($rec, $format_utf8) = @_;  =head2 rec
429    
430          my $log = $self->_get_logger();  syntaxtic sugar for
431    
432          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);    @v = rec('200')
433          return if (! $format_utf8);    @v = rec('200','a')
434    
435          my $i = 0;  =cut
         my @arr;  
436    
437          while (my @v = $self->fill_in($rec,$format_utf8,$i++)) {  sub rec {
438                  push @arr, @v;          if ($#_ == 0) {
439                    return rec1(@_);
440            } elsif ($#_ == 1) {
441                    return rec2(@_);
442          }          }
   
         $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  
   
         return @arr;  
443  }  }
444    
445    =head2 regex
446    
447  =head2 get_data  Apply regex to some or all values
   
 Returns value from record.  
448    
449   my $text = $self->get_data(\$rec,$f,$sf,$i,\$found);    @v = regex( 's/foo/bar/g', @v );
   
 Arguments are:  
 record reference C<$rec>,  
 field C<$f>,  
 optional subfiled C<$sf>,  
 index for repeatable values C<$i>.  
   
 Optinal variable C<$found> will be incremeted if there  
 is field.  
   
 Returns value or empty string.  
450    
451  =cut  =cut
452    
453  sub get_data {  sub regex {
454          my $self = shift;          my $r = shift;
455            my @out;
456          my ($rec,$f,$sf,$i,$found) = @_;          #warn "r: $r\n", dump(\@_);
457            foreach my $t (@_) {
458          if ($$rec->{$f}) {                  next unless ($t);
459                  return '' if (! $$rec->{$f}->[$i]);                  eval "\$t =~ $r";
460                  no strict 'refs';                  push @out, $t if ($t && $t ne '');
                 if ($sf && $$rec->{$f}->[$i]->{$sf}) {  
                         $$found++ if (defined($$found));  
                         return $$rec->{$f}->[$i]->{$sf};  
                 } elsif (! $sf && $$rec->{$f}->[$i]) {  
                         $$found++ if (defined($$found));  
                         # it still might have subfield, just  
                         # not specified, so we'll dump all  
                         if ($$rec->{$f}->[$i] =~ /HASH/o) {  
                                 my $out;  
                                 foreach my $k (keys %{$$rec->{$f}->[$i]}) {  
                                         $out .= $$rec->{$f}->[$i]->{$k}." ";  
                                 }  
                                 return $out;  
                         } else {  
                                 return $$rec->{$f}->[$i];  
                         }  
                 } else {  
                         return '';  
                 }  
         } else {  
                 return '';  
461          }          }
462            return @out;
463  }  }
464    
465    =head2 prefix
466    
467  =head2 apply_format  Prefix all values with a string
   
 Apply format specified in tag with C<format_name="name"> and  
 C<format_delimiter=";;">.  
   
  my $text = $webpac->apply_format($format_name,$format_delimiter,$data);  
468    
469  Formats can contain C<lookup{...}> if you need them.    @v = prefix( 'my_', @v );
470    
471  =cut  =cut
472    
473  sub apply_format {  sub prefix {
474          my $self = shift;          my $p = shift or die "prefix needs string as first argument";
475            return map { $p . $_ } grep { defined($_) } @_;
476          my ($name,$delimiter,$data) = @_;  }
   
         my $log = $self->_get_logger();  
   
         if (! $self->{'import_xml'}->{'format'}->{$name}) {  
                 $log->warn("<format name=\"$name\"> is not defined in ",$self->{'import_xml_file'});  
                 return $data;  
         }  
   
         $log->warn("no delimiter for format $name") if (! $delimiter);  
477    
478          my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'");  =head2 suffix
479    
480          my @data = split(/\Q$delimiter\E/, $data);  suffix all values with a string
481    
482          my $out = sprintf($format, @data);    @v = suffix( '_my', @v );
         $log->debug("using format $name [$format] on $data to produce: $out");  
483    
484          if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) {  =cut
                 return $self->{'lookup'}->lookup($out);  
         } else {  
                 return $out;  
         }  
485    
486    sub suffix {
487            my $s = shift or die "suffix needs string as first argument";
488            return map { $_ . $s } grep { defined($_) } @_;
489  }  }
490    
491  =head2 sort_arr  =head2 surround
492    
493  Sort array ignoring case and html in data  surround all values with a two strings
494    
495   my @sorted = $webpac->sort_arr(@unsorted);    @v = surround( 'prefix_', '_suffix', @v );
496    
497  =cut  =cut
498    
499  sub sort_arr {  sub surround {
500          my $self = shift;          my $p = shift or die "surround need prefix as first argument";
501            my $s = shift or die "surround needs suffix as second argument";
502          my $log = $self->_get_logger();          return map { $p . $_ . $s } grep { defined($_) } @_;
   
         # 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;  
503  }  }
504    
505    =head2 first
506    
507  =head1 INTERNAL METHODS  Return first element
   
 =head2 _sort_by_order  
508    
509  Sort xml tags data structure accoding to C<order=""> attribute.    $v = first( @v );
510    
511  =cut  =cut
512    
513  sub _sort_by_order {  sub first {
514          my $self = shift;          my $r = shift;
515            return $r;
         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;  
516  }  }
517    
518  =head2 _x  =head2 lookup
519    
520  Convert strings from C<conf/normalize/*.xml> encoding into application  Consult lookup hashes for some value
 specific encoding (optinally specified using C<code_page> to C<new>  
 constructor).  
521    
522   my $text = $n->_x('normalize text string');    @v = lookup( $v );
523      @v = lookup( @v );
 This is a stub so that other modules doesn't have to implement it.  
524    
525  =cut  =cut
526    
527  sub _x {  sub lookup {
528          my $self = shift;          my $k = shift or return;
529          return shift;          return unless (defined($lookup->{$k}));
530            if (ref($lookup->{$k}) eq 'ARRAY') {
531                    return @{ $lookup->{$k} };
532            } else {
533                    return $lookup->{$k};
534            }
535  }  }
536    
537    =head2 join_with
538    
539  =head1 AUTHOR  Joins walues with some delimiter
   
 Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>  
540    
541  =head1 COPYRIGHT & LICENSE    $v = join_with(", ", @v);
   
 Copyright 2005 Dobrica Pavlinusic, All Rights Reserved.  
   
 This program is free software; you can redistribute it and/or modify it  
 under the same terms as Perl itself.  
542    
543  =cut  =cut
544    
545  1; # End of WebPAC::Normalize  sub join_with {
546            my $d = shift;
547            return join($d, grep { defined($_) && $_ ne '' } @_);
548    }
549    
550    # END
551    1;

Legend:
Removed from v.268  
changed lines
  Added in v.550

  ViewVC Help
Powered by ViewVC 1.1.26