/[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 18 by dpavlin, Sun Jul 17 14:53:37 2005 UTC revision 547 by dpavlin, Thu Jun 29 23:19:26 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    
18    #use base qw/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.01  Version 0.06
29    
30  =cut  =cut
31    
32  our $VERSION = '0.01';  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<marc>.
   
 =item *  
   
 source data records (C<$rec>) have unique identifiers in field C<000>  
   
 =item *  
47    
48  optional C<eval{length('v123^a') == 3}> tag at B<beginning of format> will be  =head1 FUNCTIONS
 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  
49    
50  =item *  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  optional C<lookup{...}> will be then performed. See C<WebPAC::Lookups>.  =head2 data_structure
54    
55  =item *  Return data structure
56    
57  at end, optional C<format>s rules are resolved. Format rules are similar to    my $ds = WebPAC::Normalize::data_structure(
58  C<sprintf> and can also contain C<lookup{...}> which is performed after          lookup => $lookup->lookup_hash,
59  values are inserted in format.          row => $row,
60            rules => $normalize_pl_config,
61            marc_encoding => 'utf-8',
62      );
63    
64  =back  Options C<lookup>, C<row>, C<rules> and C<log> are mandatory while all
65    other are optional.
66    
67  This also describes order in which transformations are applied (eval,  This function will B<die> if normalizastion can't be evaled.
 filter, lookup, format) which is important to undestand when deciding how to  
 solve your data mungling and normalisation process.  
68    
69    Since this function isn't exported you have to call it with
70    C<WebPAC::Normalize::data_structure>.
71    
72    =cut
73    
74    sub data_structure {
75            my $arg = {@_};
76    
77  =head1 FUNCTIONS          die "need row argument" unless ($arg->{row});
78            die "need normalisation argument" unless ($arg->{rules});
79    
80  =head2 new          no strict 'subs';
81            _set_lookup( $arg->{lookup} );
82            _set_rec( $arg->{row} );
83            _clean_ds( %{ $arg } );
84            eval "$arg->{rules}";
85            die "error evaling $arg->{rules}: $@\n" if ($@);
86    
87  Create new normalisation object          return _get_ds();
88    }
89    
90    my $n = new WebPAC::Normalize::Something(  =head2 _set_rec
         filter => {  
                 'filter_name_1' => sub {  
                         # filter code  
                         return length($_);  
                 }, ...  
         },  
         db => $webpac_db_obj,  
         lookup_regex => $lookup->regex,  
   );  
91    
92  Parametar C<filter> defines user supplied snippets of perl code which can  Set current record hash
 be use with C<filter{...}> notation.  
93    
94  Recommended parametar C<lookup_regex> is used to enable parsing of lookups    _set_rec( $rec );
 in structures.  
95    
96  =cut  =cut
97    
98  sub new {  my $rec;
         my $class = shift;  
         my $self = {@_};  
         bless($self, $class);  
99    
100          $self ? return $self : return undef;  sub _set_rec {
101            $rec = shift or die "no record hash";
102  }  }
103    
104    =head2 _get_ds
105    
106  =head2 data_structure  Return hash formatted as data structure
   
 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);  
107    
108  B<Note: historical oddity follows>    my $ds = _get_ds();
   
 This method will also set C<< $webpac->{'currnet_filename'} >> if there is  
 C<< <filename> >> tag and C<< $webpac->{'headline'} >> if there is  
 C<< <headline> >> tag.  
109    
110  =cut  =cut
111    
112  sub data_structure {  my ($out,$marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators);
         my $self = shift;  
113    
114          my $log = $self->_get_logger();  sub _get_ds {
115            return $out;
116          my $rec = shift;  }
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
   
         my $cache_file;  
   
         if ($self->{'db'}) {  
                 my @ds = $self->{'db'}->get_ds($rec);  
                 return @ds if (@ds);  
         }  
117    
118          undef $self->{'currnet_filename'};  =head2 _clean_ds
         undef $self->{'headline'};  
119    
120          my @sorted_tags;  Clean data structure hash for next record
         if ($self->{tags_by_order}) {  
                 @sorted_tags = @{$self->{tags_by_order}};  
         } else {  
                 @sorted_tags = sort { $self->_sort_by_order } keys %{$self->{'import_xml'}->{'indexer'}};  
                 $self->{tags_by_order} = \@sorted_tags;  
         }  
121    
122          my @ds;    _clean_ds();
123    
124          $log->debug("tags: ",sub { join(", ",@sorted_tags) });  =cut
125    
126          foreach my $field (@sorted_tags) {  sub _clean_ds {
127            my $a = {@_};
128            ($out,$marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators) = (undef);
129            $marc_encoding = $a->{marc_encoding};
130    }
131    
132                  my $row;  =head2 _set_lookup
133    
134  #print "field $field [",$self->{'tag'},"] = ",Dumper($self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}});  Set current lookup hash
135    
136                  foreach my $tag (@{$self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}}) {    _set_lookup( $lookup );
                         my $format = $tag->{'value'} || $tag->{'content'};  
137    
138                          $log->debug("format: $format");  =cut
139    
140                          my @v;  my $lookup;
                         if ($self->{'lookup_regex'} && $format =~ $self->{'lookup_regex'}) {  
                                 @v = $self->fill_in_to_arr($rec,$format);  
                         } else {  
                                 @v = $self->parse_to_arr($rec,$format);  
                         }  
                         next if (! @v);  
141    
142                          if ($tag->{'sort'}) {  sub _set_lookup {
143                                  @v = $self->sort_arr(@v);          $lookup = shift;
144                          }  }
145    
146                          # use format?  =head2 _get_marc_fields
                         if ($tag->{'format_name'}) {  
                                 @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v;  
                         }  
147    
148                          if ($field eq 'filename') {  Get all fields defined by calls to C<marc>
                                 $self->{'current_filename'} = join('',@v);  
                                 $log->debug("filename: ",$self->{'current_filename'});  
                         } elsif ($field eq 'headline') {  
                                 $self->{'headline'} .= join('',@v);  
                                 $log->debug("headline: ",$self->{'headline'});  
                                 next; # don't return headline in data_structure!  
                         }  
149    
150                          # delimiter will join repeatable fields          $marc->add_fields( WebPAC::Normalize:_get_marc_fields() );
                         if ($tag->{'delimiter'}) {  
                                 @v = ( join($tag->{'delimiter'}, @v) );  
                         }  
151    
                         # default types  
                         my @types = qw(display swish);  
                         # 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;  
                                 }  
                         }  
152    
153    
154                  }  We are using I<magic> which detect repeatable fields only from
155    sequence of field/subfield data generated by normalization.
156    
157                  if ($row) {  Repeatable field is created if there is second occurence of same subfield or
158                          $row->{'tag'} = $field;  if any of indicators are different. This is sane for most cases except for
159    non-repeatable fields with repeatable subfields.
160    
161                          # TODO: name_sigular, name_plural  You can change behaviour of that using C<marc_repeatable_subfield>.
                         my $name = $self->{'import_xml'}->{'indexer'}->{$field}->{'name'};  
                         $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");  
                         }  
162    
163                          push @ds, $row;  =cut
164    
165                          $log->debug("row $field: ",sub { Dumper($row) });  sub _get_marc_fields {
166            my @m;
167            my $last;
168            foreach my $row (@{ $marc_record }) {
169                    if ($last &&
170                            $last->[0] eq $row->[0] &&              # check if field is same
171                            $last->[1] eq $row->[1] &&              # check for i1
172                            $last->[2] eq $row->[2] &&              # and for i2
173                                    ( $last->[3] ne $row->[3] ||                            # and subfield is different
174                                    $last->[3] eq $row->[3] &&                                      # or subfield is same,
175                                    $marc_repeatable_subfield->{ $row->[3] }        # but is repeatable
176                            )
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'}->put_gs(          push @m, $last if ($last);
                 ds => \@ds,  
                 current_filename => $self->{'current_filename'},  
                 headline => $self->{'headline'},  
         ) if ($self->{'db'});  
   
         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  =cut  Define new tag for I<search> and I<display>.
   
 sub parse {  
         my $self = shift;  
200    
201          my ($rec, $format_utf8, $i) = @_;    tag('Title', rec('200','a') );
202    
         return if (! $format_utf8);  
203    
204          my $log = $self->_get_logger();  =cut
   
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
205    
206          $i = 0 if (! $i);  sub tag {
207            my $name = shift or die "tag needs name as first argument";
208            my @o = grep { defined($_) && $_ ne '' } @_;
209            return unless (@o);
210            $out->{$name}->{tag} = $name;
211            $out->{$name}->{search} = \@o;
212            $out->{$name}->{display} = \@o;
213    }
214    
215          my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'});  =head2 display
216    
217          my @out;  Define tag just for I<display>
218    
219          $log->debug("format: $format");    @v = display('Title', rec('200','a') );
220    
221          my $eval_code;  =cut
         # remove eval{...} from beginning  
         $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);  
222    
223          my $filter_name;  sub display {
224          # remove filter{...} from beginning          my $name = shift or die "display needs name as first argument";
225          $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);          my @o = grep { defined($_) && $_ ne '' } @_;
226            return unless (@o);
227            $out->{$name}->{tag} = $name;
228            $out->{$name}->{display} = \@o;
229    }
230    
231          my $prefix;  =head2 search
         my $all_found=0;  
232    
233          while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) {  Prepare values just for I<search>
234    
235                  my $del = $1 || '';    @v = search('Title', rec('200','a') );
                 $prefix ||= $del if ($all_found == 0);  
236    
237                  # repeatable index  =cut
                 my $r = $i;  
                 $r = 0 if (lc("$2") eq 's');  
238    
239                  my $found = 0;  sub search {
240                  my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found);          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 marc
                         push @out, $del;  
                         push @out, $tmp;  
                         $all_found += $found;  
                 }  
         }  
248    
249          return if (! $all_found);  Save value for MARC field
250    
251          my $out = join('',@out);    marc('900','a', rec('200','a') );
252    
253          if ($out) {  =cut
                 # add rest of format (suffix)  
                 $out .= $format;  
254    
255                  # add prefix if not there  sub marc {
256                  $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/);          my $f = shift or die "marc needs field";
257            die "marc field must be numer" unless ($f =~ /^\d+$/);
258    
259                  $log->debug("result: $out");          my $sf = shift or die "marc needs subfield";
         }  
260    
261          if ($eval_code) {          foreach (@_) {
262                  my $eval = $self->fill_in($rec,$eval_code,$i) || return;                  my $v = $_;             # make var read-write for Encode
263                  $log->debug("about to eval{$eval} format: $out");                  next unless (defined($v) && $v !~ /^\s*$/);
264                  return if (! $self->_eval($eval));                  from_to($v, 'iso-8859-2', $marc_encoding) if ($marc_encoding);
265          }                  push @{ $marc_record }, [
266                                    $f,
267          if ($filter_name && $self->{'filter'}->{$filter_name}) {                          $marc_indicators->{$f}->{i1} || ' ',
268                  $log->debug("about to filter{$filter_name} format: $out");                          $marc_indicators->{$f}->{i2} || ' ',
269                  $out = $self->{'filter'}->{$filter_name}->($out);                          $sf => $v
270                  return unless(defined($out));                  ];
                 $log->debug("filter result: $out");  
271          }          }
   
         return $out;  
272  }  }
273    
274  =head2 parse_to_arr  =head2 marc_repeatable_subfield
275    
276  Similar to C<parse>, but returns array of all repeatable fields  Save values for MARC repetable subfield
277    
278   my @arr = $webpac->parse_to_arr($rec,'v250^a');    marc_repeatable_subfield('910', 'z', rec('909') );
279    
280  =cut  =cut
281    
282  sub parse_to_arr {  sub marc_repeatable_subfield {
283          my $self = shift;          die "marc_repeatable_subfield need subfield!\n" unless (defined($_[1]));
284            $marc_repeatable_subfield->{ $_[1] }++;
285            marc(@_);
286    }
287    
288          my ($rec, $format_utf8) = @_;  =head2 marc_indicators
289    
290          my $log = $self->_get_logger();  Set both indicators for MARC field
291    
292          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);    marc_indicators('900', ' ', 1);
         return if (! $format_utf8);  
293    
294          my $i = 0;  Any indicator value other than C<0-9> will be treated as undefined.
         my @arr;  
295    
296          while (my $v = $self->parse($rec,$format_utf8,$i++)) {  =cut
                 push @arr, $v;  
         }  
297    
298          $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  sub marc_indicators {
299            my $f = shift || die "marc_indicators need field!\n";
300            my ($i1,$i2) = @_;
301            die "marc_indicators($f, ...) need i1!\n" unless(defined($i1));
302            die "marc_indicators($f, $i1, ...) need i2!\n" unless(defined($i2));
303    
304          return @arr;          $i1 = ' ' if ($i1 !~ /^\d$/);
305            $i2 = ' ' if ($i2 !~ /^\d$/);
306            $marc_indicators->{$f}->{i1} = $i1;
307            $marc_indicators->{$f}->{i2} = $i2;
308  }  }
309    
310    
311  =head2 fill_in  =head1 Functions to extract data from input
   
 Workhourse of all: takes record from in-memory structure of database and  
 strings with placeholders and returns string or array of with substituted  
 values from record.  
312    
313   my $text = $webpac->fill_in($rec,'v250^a');  This function should be used inside functions to create C<data_structure> described
314    above.
315    
316  Optional argument is ordinal number for repeatable fields. By default,  =head2 rec1
 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.  
317    
318   my $text = $webpac->fill_in($rec,'Title: v250^a',1);  Return all values in some field
319    
320  This function B<does not> perform parsing of format to inteligenty skip    @v = rec1('200')
 delimiters before fields which aren't used.  
321    
322  This method will automatically decode UTF-8 string to local code page  TODO: order of values is probably same as in source data, need to investigate that
 if needed.  
323    
324  =cut  =cut
325    
326  sub fill_in {  sub rec1 {
327          my $self = shift;          my $f = shift;
328            return unless (defined($rec) && defined($rec->{$f}));
329          my $log = $self->_get_logger();          if (ref($rec->{$f}) eq 'ARRAY') {
330                    return map {
331          my $rec = shift || $log->logconfess("need data record");                          if (ref($_) eq 'HASH') {
332          my $format = shift || $log->logconfess("need format to parse");                                  values %{$_};
333          # iteration (for repeatable fields)                          } else {
334          my $i = shift || 0;                                  $_;
335                            }
336          $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999));                  } @{ $rec->{$f} };
337            } elsif( defined($rec->{$f}) ) {
338          # FIXME remove for speedup?                  return $rec->{$f};
         $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'}) {  
                         return $self->lookup($format);  
                 } else {  
                         return $format;  
                 }  
         } else {  
                 return;  
339          }          }
340  }  }
341    
342    =head2 rec2
343    
344  =head2 fill_in_to_arr  Return all values in specific field and subfield
345    
346  Similar to C<fill_in>, but returns array of all repeatable fields. Usable    @v = rec2('200','a')
 for fields which have lookups, so they shouldn't be parsed but rather  
 C<fill_id>ed.  
   
  my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]');  
347    
348  =cut  =cut
349    
350  sub fill_in_to_arr {  sub rec2 {
351          my $self = shift;          my $f = shift;
352            return unless (defined($rec && $rec->{$f}));
353            my $sf = shift;
354            return map { $_->{$sf} } grep { ref($_) eq 'HASH' && $_->{$sf} } @{ $rec->{$f} };
355    }
356    
357          my ($rec, $format_utf8) = @_;  =head2 rec
358    
359          my $log = $self->_get_logger();  syntaxtic sugar for
360    
361          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);    @v = rec('200')
362          return if (! $format_utf8);    @v = rec('200','a')
363    
364          my $i = 0;  =cut
         my @arr;  
365    
366          while (my @v = $self->fill_in($rec,$format_utf8,$i++)) {  sub rec {
367                  push @arr, @v;          if ($#_ == 0) {
368                    return rec1(@_);
369            } elsif ($#_ == 1) {
370                    return rec2(@_);
371          }          }
   
         $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  
   
         return @arr;  
372  }  }
373    
374    =head2 regex
375    
376  =head2 get_data  Apply regex to some or all values
   
 Returns value from record.  
   
  my $text = $self->get_data(\$rec,$f,$sf,$i,\$found);  
   
 Arguments are:  
 record reference C<$rec>,  
 field C<$f>,  
 optional subfiled C<$sf>,  
 index for repeatable values C<$i>.  
377    
378  Optinal variable C<$found> will be incremeted if there    @v = regex( 's/foo/bar/g', @v );
 is field.  
   
 Returns value or empty string.  
379    
380  =cut  =cut
381    
382  sub get_data {  sub regex {
383          my $self = shift;          my $r = shift;
384            my @out;
385          my ($rec,$f,$sf,$i,$found) = @_;          #warn "r: $r\n",Dumper(\@_);
386            foreach my $t (@_) {
387          if ($$rec->{$f}) {                  next unless ($t);
388                  return '' if (! $$rec->{$f}->[$i]);                  eval "\$t =~ $r";
389                  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 ($$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 '';  
390          }          }
391            return @out;
392  }  }
393    
394    =head2 prefix
395    
396  =head2 apply_format  Prefix all values with a string
   
 Apply format specified in tag with C<format_name="name"> and  
 C<format_delimiter=";;">.  
397    
398   my $text = $webpac->apply_format($format_name,$format_delimiter,$data);    @v = prefix( 'my_', @v );
   
 Formats can contain C<lookup{...}> if you need them.  
399    
400  =cut  =cut
401    
402  sub apply_format {  sub prefix {
403          my $self = shift;          my $p = shift or die "prefix needs string as first argument";
404            return map { $p . $_ } grep { defined($_) } @_;
405          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);  
406    
407          my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'");  =head2 suffix
408    
409          my @data = split(/\Q$delimiter\E/, $data);  suffix all values with a string
410    
411          my $out = sprintf($format, @data);    @v = suffix( '_my', @v );
         $log->debug("using format $name [$format] on $data to produce: $out");  
412    
413          if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) {  =cut
                 return $self->lookup($out);  
         } else {  
                 return $out;  
         }  
414    
415    sub suffix {
416            my $s = shift or die "suffix needs string as first argument";
417            return map { $_ . $s } grep { defined($_) } @_;
418  }  }
419    
420  =head2 sort_arr  =head2 surround
421    
422  Sort array ignoring case and html in data  surround all values with a two strings
423    
424   my @sorted = $webpac->sort_arr(@unsorted);    @v = surround( 'prefix_', '_suffix', @v );
425    
426  =cut  =cut
427    
428  sub sort_arr {  sub surround {
429          my $self = shift;          my $p = shift or die "surround need prefix as first argument";
430            my $s = shift or die "surround needs suffix as second argument";
431          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;  
432  }  }
433    
434    =head2 first
435    
436  =head1 INTERNAL METHODS  Return first element
437    
438  =head2 _sort_by_order    $v = first( @v );
   
 Sort xml tags data structure accoding to C<order=""> attribute.  
439    
440  =cut  =cut
441    
442  sub _sort_by_order {  sub first {
443          my $self = shift;          my $r = shift;
444            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;  
445  }  }
446    
447  =head2 _x  =head2 lookup
   
 Convert strings from C<conf/normalize/*.xml> encoding into application  
 specific encoding (optinally specified using C<code_page> to C<new>  
 constructor).  
448    
449   my $text = $n->_x('normalize text string');  Consult lookup hashes for some value
450    
451  This is a stub so that other modules doesn't have to implement it.    @v = lookup( $v );
452      @v = lookup( @v );
453    
454  =cut  =cut
455    
456  sub _x {  sub lookup {
457          my $self = shift;          my $k = shift or return;
458          return shift;          return unless (defined($lookup->{$k}));
459            if (ref($lookup->{$k}) eq 'ARRAY') {
460                    return @{ $lookup->{$k} };
461            } else {
462                    return $lookup->{$k};
463            }
464  }  }
465    
466    =head2 join_with
467    
468  =head1 AUTHOR  Joins walues with some delimiter
   
 Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>  
   
 =head1 COPYRIGHT & LICENSE  
469    
470  Copyright 2005 Dobrica Pavlinusic, All Rights Reserved.    $v = join_with(", ", @v);
   
 This program is free software; you can redistribute it and/or modify it  
 under the same terms as Perl itself.  
471    
472  =cut  =cut
473    
474  1; # End of WebPAC::DB  sub join_with {
475            my $d = shift;
476            return join($d, grep { defined($_) && $_ ne '' } @_);
477    }
478    
479    # END
480    1;

Legend:
Removed from v.18  
changed lines
  Added in v.547

  ViewVC Help
Powered by ViewVC 1.1.26