/[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 433 by dpavlin, Mon Apr 17 16:01:12 2006 UTC revision 544 by dpavlin, Thu Jun 29 21:52:51 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            marc21
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 blib;  
18  use WebPAC::Common;  #use base qw/WebPAC::Common/;
 use base 'WebPAC::Common';  
19  use Data::Dumper;  use Data::Dumper;
20    use Encode qw/from_to/;
21    
22  =head1 NAME  =head1 NAME
23    
24  WebPAC::Normalize - data mungling for normalisation  WebPAC::Normalize - describe normalisaton rules using sets
25    
26  =head1 VERSION  =head1 VERSION
27    
28  Version 0.09  Version 0.06
29    
30  =cut  =cut
31    
32  our $VERSION = '0.09';  our $VERSION = '0.06';
33    
34  =head1 SYNOPSIS  =head1 SYNOPSIS
35    
36  This package contains code that mungle data to produce normalized format.  This module uses C<conf/normalize/*.pl> files to perform normalisation
37    from input records using perl functions which are specialized for set
38  It contains several assumptions:  processing.
39    
40  =over  Sets are implemented as arrays, and normalisation file is valid perl, which
41    means that you check it's validity before running WebPAC using
42  =item *  C<perl -c normalize.pl>.
43    
44  format of fields is defined using C<v123^a> notation for repeatable fields  Normalisation can generate multiple output normalized data. For now, supported output
45  or C<s123^a> for single (or first) value, where C<123> is field number and  types (on the left side of definition) are: C<tag>, C<display>, C<search> and
46  C<a> is subfield.  C<marc21>.
   
 =item *  
   
 source data records (C<$rec>) have unique identifiers in field C<000>  
   
 =item *  
   
 optional C<eval{length('v123^a') == 3}> tag at B<beginning of format> will be  
 perl code that is evaluated before producing output (value of field will be  
 interpolated before that)  
   
 =item *  
   
 optional C<filter{filter_name}> at B<begining of format> will apply perl  
 code defined as code ref on format after field substitution to producing  
 output  
   
 There is one built-in filter called C<regex> which can be use like this:  
   
   filter{regex(s/foo/bar/)}  
   
 =item *  
   
 optional C<lookup{...}> will be then performed. See C<WebPAC::Lookups>.  
   
 =item *  
   
 at end, optional C<format>s rules are resolved. Format rules are similar to  
 C<sprintf> and can also contain C<lookup{...}> which is performed after  
 values are inserted in format.  
   
 =back  
   
 This also describes order in which transformations are applied (eval,  
 filter, lookup, format) which is important to undestand when deciding how to  
 solve your data mungling and normalisation process.  
   
   
   
47    
48  =head1 FUNCTIONS  =head1 FUNCTIONS
49    
50  =head2 new  Functions which start with C<_> are private and used by WebPAC internally.
51    All other functions are available for use within normalisation rules.
52    
53    =head2 data_structure
54    
55  Create new normalisation object  Return data structure
56    
57    my $n = new WebPAC::Normalize::Something(    my $ds = WebPAC::Normalize::data_structure(
58          filter => {          lookup => $lookup->lookup_hash,
59                  'filter_name_1' => sub {          row => $row,
60                          # filter code          rules => $normalize_pl_config,
61                          return length($_);          marc_encoding => 'utf-8',
                 }, ...  
         },  
         db => $db_obj,  
         lookup_regex => $lookup->regex,  
         lookup => $lookup_obj,  
         prefix => 'foobar',  
62    );    );
63    
64  Parametar C<filter> defines user supplied snippets of perl code which can  Options C<lookup>, C<row>, C<rules> and C<log> are mandatory while all
65  be use with C<filter{...}> notation.  other are optional.
66    
67  C<prefix> is used to form filename for database record (to support multiple  This function will B<die> if normalizastion can't be evaled.
 source files which are joined in one database).  
68    
69  Recommended parametar C<lookup_regex> is used to enable parsing of lookups  Since this function isn't exported you have to call it with
70  in structures. If you pass this parametar, you must also pass C<lookup>  C<WebPAC::Normalize::data_structure>.
 which is C<WebPAC::Lookup> object.  
71    
72  =cut  =cut
73    
74  sub new {  sub data_structure {
75          my $class = shift;          my $arg = {@_};
         my $self = {@_};  
         bless($self, $class);  
   
         my $r = $self->{'lookup_regex'} ? 1 : 0;  
         my $l = $self->{'lookup'} ? 1 : 0;  
   
         my $log = $self->_get_logger();  
   
         # those two must be in pair  
         if ( ($r & $l) != ($r || $l) ) {  
                 my $log = $self->_get_logger();  
                 $log->logdie("lookup_regex and lookup must be in pair");  
         }  
   
         $log->logdie("lookup must be WebPAC::Lookup object") if ($self->{'lookup'} && ! $self->{'lookup'}->isa('WebPAC::Lookup'));  
   
         $log->warn("no prefix defined. please check that!") unless ($self->{'prefix'});  
76    
77          $log->debug("using lookup regex: ", $self->{lookup_regex}) if ($r && $l);          die "need row argument" unless ($arg->{row});
78            die "need normalisation argument" unless ($arg->{rules});
79    
80          if (! $self->{filter} || ! $self->{filter}->{regex}) {          no strict 'subs';
81                  $log->debug("adding built-in filter regex");          _set_lookup( $arg->{lookup} );
82                  $self->{filter}->{regex} = sub {          _set_rec( $arg->{row} );
83                          my ($val, $regex) = @_;          _clean_ds( %{ $arg } );
84                          eval "\$val =~ $regex";          eval "$arg->{rules}";
85                          return $val;          die "error evaling $arg->{rules}: $@\n" if ($@);
                 };  
         }  
86    
87          $self ? return $self : return undef;          return _get_ds();
88  }  }
89    
90  =head2 all_tags  =head2 _set_rec
91    
92  Returns all tags in document in specified order  Set current record hash
93    
94    my $sorted_tags = $self->all_tags();    _set_rec( $rec );
95    
96  =cut  =cut
97    
98  sub all_tags {  my $rec;
         my $self = shift;  
   
         if (! $self->{_tags_by_order}) {  
   
                 my $log = $self->_get_logger;  
                 # sanity check  
                 $log->logdie("can't find self->{inport_xml}->{indexer}") unless ($self->{import_xml}->{indexer});  
   
                 my @tags = keys %{ $self->{'import_xml'}->{'indexer'}};  
                 $log->debug("unsorted tags: " . join(", ", @tags));  
99    
100                  @tags = sort { $self->_sort_by_order } @tags;  sub _set_rec {
101            $rec = shift or die "no record hash";
                 $log->debug("sorted tags: " . join(",", @tags) );  
   
                 $self->{_tags_by_order} = \@tags;  
         }  
   
         return $self->{_tags_by_order};  
102  }  }
103    
104    =head2 _get_ds
105    
106    Return hash formatted as data structure
107    
108  =head2 data_structure    my $ds = _get_ds();
   
 Create in-memory data structure which represents normalized layout from  
 C<conf/normalize/*.xml>.  
   
 This structures are used to produce output.  
   
  my $ds = $webpac->data_structure($rec);  
109    
110  =cut  =cut
111    
112  sub data_structure {  my $out;
113          my $self = shift;  my $marc21;
114    my $marc_encoding;
         my $log = $self->_get_logger();  
   
         my $rec = shift;  
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
115    
116          $log->debug("data_structure rec = ", sub { Dumper($rec) });  sub _get_ds {
117            return $out;
118          $log->logdie("need unique ID (mfn) in field 000 of record " . Dumper($rec) ) unless (defined($rec->{'000'}));  }
   
         my $id = $rec->{'000'}->[0] || $log->logdie("field 000 isn't array!");  
119    
120          my $cache_file;  =head2 _clean_ds
121    
122          if ($self->{'db'}) {  Clean data structure hash for next record
                 my $ds = $self->{'db'}->load_ds( id => $id, prefix => $self->{prefix} );  
                 $log->debug("load_ds( rec = ", sub { Dumper($rec) }, ") = ", sub { Dumper($ds) });  
                 return $ds if ($ds);  
                 $log->debug("cache miss, creating");  
         }  
123    
124          my $tags = $self->all_tags();    _clean_ds();
125    
126          $log->debug("tags: ",sub { join(", ",@{ $tags }) });  =cut
127    
128          my $ds;  sub _clean_ds {
129            my $a = {@_};
130            $out = undef;
131            $marc21 = undef;
132            $marc_encoding = $a->{marc_encoding};
133    }
134    
135          foreach my $field (@{ $tags }) {  =head2 _set_lookup
136    
137                  my $row;  Set current lookup hash
138    
139  #print "field $field [",$self->{'tag'},"] = ",Dumper($self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}});    _set_lookup( $lookup );
140    
141                  foreach my $tag (@{$self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}}) {  =cut
                         my $format;  
142    
143                          $log->logdie("expected tag HASH and got $tag") unless (ref($tag) eq 'HASH');  my $lookup;
                         $format = $tag->{'value'} || $tag->{'content'};  
144    
145                          my @v;  sub _set_lookup {
146                          if ($self->{'lookup_regex'} && $format =~ $self->{'lookup_regex'}) {          $lookup = shift;
147                                  @v = $self->_rec_to_arr($rec,$format,'fill_in');  }
                         } else {  
                                 @v = $self->_rec_to_arr($rec,$format,'parse');  
                         }  
                         if (! @v) {  
                                 $log->debug("$field <",$self->{tag},"> format: $format no values");  
                                 next;  
                         } else {  
                                 $log->debug("$field <",$self->{tag},"> format: $format values: ", join(",", @v));  
                         }  
148    
149                          if ($tag->{'sort'}) {  =head2 _get_marc21_fields
                                 @v = $self->sort_arr(@v);  
                         }  
150    
151                          # use format?  Get all fields defined by calls to C<marc21>
                         if ($tag->{'format_name'}) {  
                                 @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v;  
                         }  
152    
153                          # delimiter will join repeatable fields          $marc->add_fields( WebPAC::Normalize:_get_marc21_fields() );
                         if ($tag->{'delimiter'}) {  
                                 @v = ( join($tag->{'delimiter'}, @v) );  
                         }  
154    
                         # default types  
                         my @types = qw(display search);  
                         # override by type attribute  
                         @types = ( $tag->{'type'} ) if ($tag->{'type'});  
   
                         foreach my $type (@types) {  
                                 # append to previous line?  
                                 $log->debug("tag $field / $type [",sub { join(",",@v) }, "] ", $row->{'append'} || 'no append');  
                                 if ($tag->{'append'}) {  
   
                                         # I will delimit appended part with  
                                         # delimiter (or ,)  
                                         my $d = $tag->{'delimiter'};  
                                         # default delimiter  
                                         $d ||= " ";  
   
                                         my $last = pop @{$row->{$type}};  
                                         $d = "" if (! $last);  
                                         $last .= $d . join($d, @v);  
                                         push @{$row->{$type}}, $last;  
   
                                 } else {  
                                         push @{$row->{$type}}, @v;  
                                 }  
                         }  
155    
156    
157                  }  We are using I<magic> which detect repeatable fields only from
158    sequence of field/subfield data generated by normalization.
159    
160                  if ($row) {  Repeatable field is created if there is second occurence of same subfield or
161                          $row->{'tag'} = $field;  if any of indicators are different. This is sane for most cases except for
162    non-repeatable fields with repeatable subfields.
163    
164                          # TODO: name_sigular, name_plural  B<TODO>: implement exceptions to magic
                         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");  
                         }  
165    
166                          $ds->{$row_name} = $row;  =cut
167    
168                          $log->debug("row $field: ",sub { Dumper($row) });  sub _get_marc21_fields {
169            my @m;
170            my $last;
171            foreach my $row (@{ $marc21 }) {
172                    if ($last &&
173                            $last->[0] eq $row->[0] &&              # check if field is same
174                            $last->[1] eq $row->[1] &&              # check for i1
175                            $last->[2] eq $row->[2] &&              # and for i2
176                            $last->[3] ne $row->[3]                 # and subfield is different
177                    ) {
178                            push @$last, ( $row->[3] , $row->[4] );
179                            warn "## ++ added $row->[0] ^$row->[3] to $last->[0]\n";
180                            next;
181                    } elsif ($last) {
182                            push @m, $last;
183                  }                  }
184    
185                    $last = $row;
186          }          }
187    
188          $self->{'db'}->save_ds(          push @m, $last if ($last);
                 id => $id,  
                 ds => $ds,  
                 prefix => $self->{prefix},  
         ) if ($self->{'db'});  
   
         $log->debug("ds: ", sub { Dumper($ds) });  
   
         $log->logconfess("data structure returned is not array any more!") if wantarray;  
   
         return $ds;  
189    
190            return @m;
191  }  }
192    
193  =head2 parse  =head1 Functions to create C<data_structure>
194    
195  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.  
196    
197   my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i);  =head2 tag
198    
199  Filters are implemented here. While simple form of filters looks like this:  Define new tag for I<search> and I<display>.
200    
201    filter{name_of_filter}    tag('Title', rec('200','a') );
202    
 but, filters can also have variable number of parametars like this:  
   
   filter{name_of_filter(param,param,param)}  
203    
204  =cut  =cut
205    
206  my $warn_once;  sub tag {
207            my $name = shift or die "tag needs name as first argument";
208  sub parse {          my @o = grep { defined($_) && $_ ne '' } @_;
209          my $self = shift;          return unless (@o);
210            $out->{$name}->{tag} = $name;
211          my ($rec, $format_utf8, $i, $rec_size) = @_;          $out->{$name}->{search} = \@o;
212            $out->{$name}->{display} = \@o;
213          return if (! $format_utf8);  }
   
         my $log = $self->_get_logger();  
   
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
   
         $i = 0 if (! $i);  
   
         my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'});  
   
         my @out;  
214    
215          $log->debug("format: $format [$i]");  =head2 display
216    
217          my $eval_code;  Define tag just for I<display>
         # remove eval{...} from beginning  
         $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);  
218    
219          my $filter_name;    @v = display('Title', rec('200','a') );
         # remove filter{...} from beginning  
         $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);  
220    
221          # did we found any (att all) field from format in row?  =cut
         my $found_any;  
         # prefix before first field which we preserve it $found_any  
         my $prefix;  
222    
223          my $f_step = 1;  sub display {
224            my $name = shift or die "display needs name as first argument";
225            my @o = grep { defined($_) && $_ ne '' } @_;
226            return unless (@o);
227            $out->{$name}->{tag} = $name;
228            $out->{$name}->{display} = \@o;
229    }
230    
231          while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) {  =head2 search
232    
233                  my $del = $1 || '';  Prepare values just for I<search>
                 $prefix = $del if ($f_step == 1);  
234    
235                  my $fld_type = lc($2);    @v = search('Title', rec('200','a') );
236    
237                  # repeatable index  =cut
                 my $r = $i;  
                 if ($fld_type eq 's') {  
                         if ($found_any->{'v'}) {  
                                 $r = 0;  
                         } else {  
                                 return;  
                         }  
                 }  
238    
239                  my $found = 0;  sub search {
240                  my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found,$rec_size);          my $name = shift or die "search needs name as first argument";
241            my @o = grep { defined($_) && $_ ne '' } @_;
242            return unless (@o);
243            $out->{$name}->{tag} = $name;
244            $out->{$name}->{search} = \@o;
245    }
246    
247                  if ($found) {  =head2 marc21
                         $found_any->{$fld_type} += $found;  
248    
249                          # we will skip delimiter before first occurence of field!  Save value for MARC field
                         push @out, $del unless($found_any->{$fld_type} == 1);  
                         push @out, $tmp;  
                 }  
                 $f_step++;  
         }  
250    
251          # test if any fields found?    marc21('900','a', rec('200','a') );
         return if (! $found_any->{'v'} && ! $found_any->{'s'});  
252    
253          my $out = join('',@out);  =cut
254    
255          if ($out) {  sub marc21 {
256                  # add rest of format (suffix)          my $f = shift or die "marc21 needs field";
257                  $out .= $format;          die "marc21 field must be numer" unless ($f =~ /^\d+$/);
258    
259                  # add prefix if not there          my $sf = shift or die "marc21 needs subfield";
                 $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/);  
260    
261                  $log->debug("result: $out");          foreach (@_) {
262                    my $v = $_;             # make var read-write for Encode
263                    next unless (defined($v) && $v !~ /^\s*$/);
264                    from_to($v, 'iso-8859-2', $marc_encoding) if ($marc_encoding);
265                    push @{ $marc21 }, [ $f, ' ', ' ', $sf => $v ];
266          }          }
   
         if ($eval_code) {  
                 my $eval = $self->fill_in($rec,$eval_code,$i) || return;  
                 $log->debug("about to eval{$eval} format: $out");  
                 return if (! $self->_eval($eval));  
         }  
           
         if ($filter_name) {  
                 my @filter_args;  
                 if ($filter_name =~ s/(\w+)\((.*)\)/$1/) {  
                         @filter_args = split(/,/, $2);  
                 }  
                 if ($self->{'filter'}->{$filter_name}) {  
                         $log->debug("about to filter{$filter_name} format: $out with arguments: ", join(",", @filter_args));  
                         unshift @filter_args, $out;  
                         $out = $self->{'filter'}->{$filter_name}->(@filter_args);  
                         return unless(defined($out));  
                         $log->debug("filter result: $out");  
                 } elsif (! $warn_once->{$filter_name}) {  
                         $log->warn("trying to use undefined filter $filter_name");  
                         $warn_once->{$filter_name}++;  
                 }  
         }  
   
         return $out;  
267  }  }
268    
269  =head2 fill_in  =head1 Functions to extract data from input
270    
271  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
272  strings with placeholders and returns string or array of with substituted  above.
 values from record.  
273    
274   my $text = $webpac->fill_in($rec,'v250^a');  =head2 rec1
275    
276  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.  
277    
278   my $text = $webpac->fill_in($rec,'Title: v250^a',1);    @v = rec1('200')
279    
280  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.  
   
 There is optional parametar C<$record_size> which can be used to get sizes of  
 all C<field^subfield> combinations in this format.  
   
  my $text = $webpac->fill_in($rec,'got: v900^a v900^x',0,\$rec_size);  
281    
282  =cut  =cut
283    
284  sub fill_in {  sub rec1 {
285          my $self = shift;          my $f = shift;
286            return unless (defined($rec) && defined($rec->{$f}));
287          my $log = $self->_get_logger();          if (ref($rec->{$f}) eq 'ARRAY') {
288                    return map {
289          my ($rec,$format,$i,$rec_size) = @_;                          if (ref($_) eq 'HASH') {
290                                    values %{$_};
         $log->logconfess("need data record") unless ($rec);  
         $log->logconfess("need format to parse") unless($format);  
   
         # iteration (for repeatable fields)  
         $i ||= 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 $just_single = 1;  
   
         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);  
   
         {  
                 # fix warnings  
                 no warnings 'uninitialized';  
   
                 # do actual replacement of placeholders  
                 # repeatable fields  
                 if ($format =~ s/v(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,$i,\$found,$rec_size)/ges) {  
                         $just_single = 0;  
                 }  
   
                 # non-repeatable fields  
                 if ($format =~ s/s(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,0,\$found,$rec_size)/ges) {  
                         return if ($i > 0 && $just_single);  
                 }  
         }  
   
         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;  
291                          } else {                          } else {
292                                  $log->warn("Have lookup object but can't invoke lookup method");                                  $_;
293                          }                          }
294                  } else {                  } @{ $rec->{$f} };
295                          return $format;          } elsif( defined($rec->{$f}) ) {
296                  }                  return $rec->{$f};
         } else {  
                 return;  
297          }          }
298  }  }
299    
300    =head2 rec2
301    
302  =head2 _rec_to_arr  Return all values in specific field and subfield
   
 Similar to C<parse> and C<fill_in>, but returns array of all repeatable fields. Usable  
 for fields which have lookups, so they shouldn't be parsed but rather  
 C<paste>d or C<fill_id>ed. Last argument is name of operation: C<paste> or C<fill_in>.  
303    
304   my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]','paste');    @v = rec2('200','a')
305    
306  =cut  =cut
307    
308  sub _rec_to_arr {  sub rec2 {
309          my $self = shift;          my $f = shift;
310            return unless (defined($rec && $rec->{$f}));
311          my ($rec, $format_utf8, $code) = @_;          my $sf = shift;
312            return map { $_->{$sf} } grep { ref($_) eq 'HASH' && $_->{$sf} } @{ $rec->{$f} };
313    }
314    
315          my $log = $self->_get_logger();  =head2 rec
316    
317          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  syntaxtic sugar for
         return if (! $format_utf8);  
318    
319          $log->debug("using $code on $format_utf8");    @v = rec('200')
320      @v = rec('200','a')
321    
322          my $i = 0;  =cut
         my $max = 0;  
         my @arr;  
         my $rec_size = {};  
323    
324          while ($i <= $max) {  sub rec {
325                  my @v = $self->$code($rec,$format_utf8,$i++,\$rec_size);          if ($#_ == 0) {
326                  if ($rec_size) {                  return rec1(@_);
327                          foreach my $f (keys %{ $rec_size }) {          } elsif ($#_ == 1) {
328                                  $max = $rec_size->{$f} if ($rec_size->{$f} > $max);                  return rec2(@_);
                         }  
                         $log->debug("max set to $max");  
                         undef $rec_size;  
                 }  
                 if (@v) {  
                         push @arr, @v;  
                 } else {  
                         push @arr, '' if ($max > $i);  
                 }  
329          }          }
   
         $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  
   
         return @arr;  
330  }  }
331    
332    =head2 regex
333    
334  =head2 get_data  Apply regex to some or all values
   
 Returns value from record.  
   
  my $text = $self->get_data(\$rec,$f,$sf,$i,\$found,\$rec_size);  
   
 Required arguments are:  
   
 =over 8  
   
 =item C<$rec>  
   
 record reference  
   
 =item C<$f>  
   
 field  
335    
336  =item C<$sf>    @v = regex( 's/foo/bar/g', @v );
   
 optional subfield  
   
 =item C<$i>  
   
 index offset for repeatable values ( 0 ... $rec_size->{'400^a'} )  
   
 =item C<$found>  
   
 optional variable that will be incremeted if preset  
   
 =item C<$rec_size>  
   
 hash to hold maximum occurances of C<field^subfield> combinations  
 (which can be accessed using keys in same format)  
   
 =back  
   
 Returns value or empty string, updates C<$found> and C<rec_size>  
 if present.  
337    
338  =cut  =cut
339    
340  sub get_data {  sub regex {
341          my $self = shift;          my $r = shift;
342            my @out;
343          my ($rec,$f,$sf,$i,$found,$cache) = @_;          #warn "r: $r\n",Dumper(\@_);
344            foreach my $t (@_) {
345          return '' unless ($$rec->{$f} && ref($$rec->{$f}) eq 'ARRAY');                  next unless ($t);
346                    eval "\$t =~ $r";
347          if (defined($$cache)) {                  push @out, $t if ($t && $t ne '');
                 $$cache->{ $f . ( $sf ? '^' . $sf : '' ) } ||= scalar @{ $$rec->{$f} };  
         }  
   
         return '' unless ($$rec->{$f}->[$i]);  
   
         {  
                 no strict 'refs';  
                 if (defined($sf)) {  
                         $$found++ if (defined($$found) && $$rec->{$f}->[$i]->{$sf});  
                         return $$rec->{$f}->[$i]->{$sf};  
                 } else {  
                         $$found++ if (defined($$found));  
                         # it still might have subfields, just  
                         # not specified, so we'll dump some debug info  
                         if ($$rec->{$f}->[$i] =~ /HASH/o) {  
                                 my $out;  
                                 foreach my $k (keys %{$$rec->{$f}->[$i]}) {  
                                         $out .= '$' . $k .':' . $$rec->{$f}->[$i]->{$k}." ";  
                                 }  
                                 return $out;  
                         } else {  
                                 return $$rec->{$f}->[$i];  
                         }  
                 }  
348          }          }
349            return @out;
350  }  }
351    
352    =head2 prefix
353    
354  =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);  
355    
356  Formats can contain C<lookup{...}> if you need them.    @v = prefix( 'my_', @v );
357    
358  =cut  =cut
359    
360  sub apply_format {  sub prefix {
361          my $self = shift;          my $p = shift or die "prefix needs string as first argument";
362            return map { $p . $_ } grep { defined($_) } @_;
363          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);  
364    
365          my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'");  =head2 suffix
366    
367          my @data = split(/\Q$delimiter\E/, $data);  suffix all values with a string
368    
369          my $out = sprintf($format, @data);    @v = suffix( '_my', @v );
         $log->debug("using format $name [$format] on $data to produce: $out");  
370    
371          if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) {  =cut
                 return $self->{'lookup'}->lookup($out);  
         } else {  
                 return $out;  
         }  
372    
373    sub suffix {
374            my $s = shift or die "suffix needs string as first argument";
375            return map { $_ . $s } grep { defined($_) } @_;
376  }  }
377    
378  =head2 sort_arr  =head2 surround
379    
380  Sort array ignoring case and html in data  surround all values with a two strings
381    
382   my @sorted = $webpac->sort_arr(@unsorted);    @v = surround( 'prefix_', '_suffix', @v );
383    
384  =cut  =cut
385    
386  sub sort_arr {  sub surround {
387          my $self = shift;          my $p = shift or die "surround need prefix as first argument";
388            my $s = shift or die "surround needs suffix as second argument";
389          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;  
390  }  }
391    
392    =head2 first
393    
394  =head1 INTERNAL METHODS  Return first element
395    
396  =head2 _sort_by_order    $v = first( @v );
   
 Sort xml tags data structure accoding to C<order=""> attribute.  
397    
398  =cut  =cut
399    
400  sub _sort_by_order {  sub first {
401          my $self = shift;          my $r = shift;
402            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;  
403  }  }
404    
405  =head2 _x  =head2 lookup
406    
407  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).  
408    
409   my $text = $n->_x('normalize text string');    @v = lookup( $v );
410      @v = lookup( @v );
 This is a stub so that other modules doesn't have to implement it.  
411    
412  =cut  =cut
413    
414  sub _x {  sub lookup {
415          my $self = shift;          my $k = shift or return;
416          return shift;          return unless (defined($lookup->{$k}));
417            if (ref($lookup->{$k}) eq 'ARRAY') {
418                    return @{ $lookup->{$k} };
419            } else {
420                    return $lookup->{$k};
421            }
422  }  }
423    
424    =head2 join_with
425    
426  =head1 AUTHOR  Joins walues with some delimiter
427    
428  Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>    $v = join_with(", ", @v);
   
 =head1 COPYRIGHT & LICENSE  
   
 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.  
429    
430  =cut  =cut
431    
432  1; # End of WebPAC::Normalize  sub join_with {
433            my $d = shift;
434            return join($d, grep { defined($_) && $_ ne '' } @_);
435    }
436    
437    # END
438    1;

Legend:
Removed from v.433  
changed lines
  Added in v.544

  ViewVC Help
Powered by ViewVC 1.1.26