/[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 252 by dpavlin, Thu Dec 15 17:01:04 2005 UTC revision 541 by dpavlin, Thu Jun 29 21:18:50 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 base 'WebPAC::Common';  
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.04  Version 0.06
29    
30  =cut  =cut
31    
32  our $VERSION = '0.04';  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  
   
 =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  Create new normalisation object  =head2 data_structure
54    
55    my $n = new WebPAC::Normalize::Something(  Return data structure
56          filter => {  
57                  'filter_name_1' => sub {    my $ds = WebPAC::Normalize::data_structure(
58                          # filter code          lookup => $lookup->lookup_hash,
59                          return length($_);          row => $row,
60                  }, ...          rules => $normalize_pl_config,
61          },          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'));  
76    
77          $log->warn("no prefix defined. please check that!") unless ($self->{'prefix'});          die "need row argument" unless ($arg->{row});
78            die "need normalisation argument" unless ($arg->{rules});
79    
80          $log->debug("using lookup regex: ", $self->{lookup_regex}) if ($r && $l);          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          $self ? return $self : return undef;          return _get_ds();
88  }  }
89    
90    =head2 _set_rec
91    
92  =head2 data_structure  Set current record hash
   
 Create in-memory data structure which represents normalized layout from  
 C<conf/normalize/*.xml>.  
   
 This structures are used to produce output.  
93    
94   my $ds = $webpac->data_structure($rec);    _set_rec( $rec );
95    
96  =cut  =cut
97    
98  sub data_structure {  my $rec;
         my $self = shift;  
   
         my $log = $self->_get_logger();  
   
         my $rec = shift;  
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
   
         $log->debug("data_structure rec = ", sub { Dumper($rec) });  
99    
100          $log->logdie("need unique ID (mfn) in field 000 of record ", sub { Dumper($rec) } ) unless (defined($rec->{'000'}));  sub _set_rec {
101            $rec = shift or die "no record hash";
102          my $id = $rec->{'000'}->[0] || $log->logdie("field 000 isn't array!");  }
   
         my $cache_file;  
   
         if ($self->{'db'}) {  
                 my $ds = $self->{'db'}->load_ds( id => $id, prefix => $self->{prefix} );  
                 $log->debug("load_ds( rec = ", sub { Dumper($rec) }, ") = ", sub { Dumper($ds) });  
                 return $ds if ($ds);  
                 $log->debug("cache miss, creating");  
         }  
   
         undef $self->{'currnet_filename'};  
         undef $self->{'headline'};  
   
         my @sorted_tags;  
         if ($self->{tags_by_order}) {  
                 @sorted_tags = @{$self->{tags_by_order}};  
         } else {  
                 @sorted_tags = sort { $self->_sort_by_order } keys %{$self->{'import_xml'}->{'indexer'}};  
                 $self->{tags_by_order} = \@sorted_tags;  
         }  
   
         my $ds;  
   
         $log->debug("tags: ",sub { join(", ",@sorted_tags) });  
   
         foreach my $field (@sorted_tags) {  
   
                 my $row;  
   
 #print "field $field [",$self->{'tag'},"] = ",Dumper($self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}});  
   
                 foreach my $tag (@{$self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}}) {  
                         my $format;  
103    
104                          $log->logdie("expected tag HASH and got $tag") unless (ref($tag) eq 'HASH');  =head2 _get_ds
                         $format = $tag->{'value'} || $tag->{'content'};  
105    
106                          $log->debug("format: $format");  Return hash formatted as data structure
107    
108                          my @v;    my $ds = _get_ds();
                         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);  
109    
110                          if ($tag->{'sort'}) {  =cut
                                 @v = $self->sort_arr(@v);  
                         }  
111    
112                          # use format?  my $out;
113                          if ($tag->{'format_name'}) {  my $marc21;
114                                  @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v;  my $marc_encoding;
                         }  
   
                         # 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;  
                                 }  
                         }  
115    
116    sub _get_ds {
117            return $out;
118    }
119    
120                  }  =head2 _clean_ds
121    
122                  if ($row) {  Clean data structure hash for next record
                         $row->{'tag'} = $field;  
123    
124                          # TODO: name_sigular, name_plural    _clean_ds();
                         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");  
                         }  
125    
126                          $ds->{$row_name} = $row;  =cut
127    
128                          $log->debug("row $field: ",sub { Dumper($row) });  sub _clean_ds {
129                  }          my $a = {@_};
130            $out = undef;
131            $marc21 = undef;
132            $marc_encoding = $a->{marc_encoding};
133    }
134    
135          }  =head2 _set_lookup
136    
137          $self->{'db'}->save_ds(  Set current lookup hash
                 id => $id,  
                 ds => $ds,  
                 prefix => $self->{prefix},  
         ) if ($self->{'db'});  
138    
139          $log->debug("ds: ", sub { Dumper($ds) });    _set_lookup( $lookup );
140    
141          $log->logconfess("data structure returned is not array any more!") if wantarray;  =cut
142    
143          return $ds;  my $lookup;
144    
145    sub _set_lookup {
146            $lookup = shift;
147  }  }
148    
149  =head2 parse  =head2 _get_marc21_fields
150    
151  Perform smart parsing of string, skipping delimiters for fields which aren't  Get all fields defined by calls to C<marc21>
 defined. It can also eval code in format starting with C<eval{...}> and  
 return output or nothing depending on eval code.  
152    
153   my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i);          $marc->add_fields( WebPAC::Normalize:_get_marc21_fields() );
154    
155  =cut  =cut
156    
157  sub parse {  sub _get_marc21_fields {
158          my $self = shift;          return @{$marc21};
159    }
         my ($rec, $format_utf8, $i) = @_;  
   
         return if (! $format_utf8);  
   
         my $log = $self->_get_logger();  
   
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
160    
161          $i = 0 if (! $i);  =head1 Functions to create C<data_structure>
162    
163          my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'});  Those functions generally have to first in your normalization file.
164    
165          my @out;  =head2 tag
166    
167          $log->debug("format: $format");  Define new tag for I<search> and I<display>.
168    
169          my $eval_code;    tag('Title', rec('200','a') );
         # remove eval{...} from beginning  
         $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);  
170    
         my $filter_name;  
         # remove filter{...} from beginning  
         $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);  
171    
172          my $prefix;  =cut
         my $all_found=0;  
173    
174          while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) {  sub tag {
175            my $name = shift or die "tag needs name as first argument";
176            my @o = grep { defined($_) && $_ ne '' } @_;
177            return unless (@o);
178            $out->{$name}->{tag} = $name;
179            $out->{$name}->{search} = \@o;
180            $out->{$name}->{display} = \@o;
181    }
182    
183                  my $del = $1 || '';  =head2 display
                 $prefix ||= $del if ($all_found == 0);  
184    
185                  # repeatable index  Define tag just for I<display>
                 my $r = $i;  
                 $r = 0 if (lc("$2") eq 's');  
186    
187                  my $found = 0;    @v = display('Title', rec('200','a') );
                 my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found);  
188    
189                  if ($found) {  =cut
                         push @out, $del;  
                         push @out, $tmp;  
                         $all_found += $found;  
                 }  
         }  
   
         return if (! $all_found);  
190    
191          my $out = join('',@out);  sub display {
192            my $name = shift or die "display needs name as first argument";
193            my @o = grep { defined($_) && $_ ne '' } @_;
194            return unless (@o);
195            $out->{$name}->{tag} = $name;
196            $out->{$name}->{display} = \@o;
197    }
198    
199          if ($out) {  =head2 search
                 # add rest of format (suffix)  
                 $out .= $format;  
200    
201                  # add prefix if not there  Prepare values just for I<search>
                 $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/);  
202    
203                  $log->debug("result: $out");    @v = search('Title', rec('200','a') );
         }  
204    
205          if ($eval_code) {  =cut
                 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 && $self->{'filter'}->{$filter_name}) {  
                 $log->debug("about to filter{$filter_name} format: $out");  
                 $out = $self->{'filter'}->{$filter_name}->($out);  
                 return unless(defined($out));  
                 $log->debug("filter result: $out");  
         }  
206    
207          return $out;  sub search {
208            my $name = shift or die "search needs name as first argument";
209            my @o = grep { defined($_) && $_ ne '' } @_;
210            return unless (@o);
211            $out->{$name}->{tag} = $name;
212            $out->{$name}->{search} = \@o;
213  }  }
214    
215  =head2 parse_to_arr  =head2 marc21
216    
217  Similar to C<parse>, but returns array of all repeatable fields  Save value for MARC field
218    
219   my @arr = $webpac->parse_to_arr($rec,'v250^a');    marc21('900','a', rec('200','a') );
220    
221  =cut  =cut
222    
223  sub parse_to_arr {  sub marc21 {
224          my $self = shift;          my $f = shift or die "marc21 needs field";
225            die "marc21 field must be numer" unless ($f =~ /^\d+$/);
         my ($rec, $format_utf8) = @_;  
226    
227          my $log = $self->_get_logger();          my $sf = shift or die "marc21 needs subfield";
228    
229          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);          foreach (@_) {
230          return if (! $format_utf8);                  my $v = $_;             # make var read-write for Encode
231                    next unless (defined($v) && $v !~ /^\s+$/);
232          my $i = 0;                  from_to($v, 'iso-8859-2', $marc_encoding) if ($marc_encoding);
233          my @arr;                  push @{ $marc21 }, [ $f, ' ', ' ', $sf => $v ];
   
         while (my $v = $self->parse($rec,$format_utf8,$i++)) {  
                 push @arr, $v;  
234          }          }
   
         $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  
   
         return @arr;  
235  }  }
236    
237    =head1 Functions to extract data from input
238    
239  =head2 fill_in  This function should be used inside functions to create C<data_structure> described
240    above.
241    
242  Workhourse of all: takes record from in-memory structure of database and  =head2 rec1
 strings with placeholders and returns string or array of with substituted  
 values from record.  
243    
244   my $text = $webpac->fill_in($rec,'v250^a');  Return all values in some field
245    
246  Optional argument is ordinal number for repeatable fields. By default,    @v = rec1('200')
 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.  
247    
248   my $text = $webpac->fill_in($rec,'Title: v250^a',1);  TODO: order of values is probably same as in source data, need to investigate that
   
 This function B<does not> perform parsing of format to inteligenty skip  
 delimiters before fields which aren't used.  
   
 This method will automatically decode UTF-8 string to local code page  
 if needed.  
249    
250  =cut  =cut
251    
252  sub fill_in {  sub rec1 {
253          my $self = shift;          my $f = shift;
254            return unless (defined($rec) && defined($rec->{$f}));
255          my $log = $self->_get_logger();          if (ref($rec->{$f}) eq 'ARRAY') {
256                    return map {
257          my $rec = shift || $log->logconfess("need data record");                          if (ref($_) eq 'HASH') {
258          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;  
259                          } else {                          } else {
260                                  $log->warn("Have lookup object but can't invoke lookup method");                                  $_;
261                          }                          }
262                  } else {                  } @{ $rec->{$f} };
263                          return $format;          } elsif( defined($rec->{$f}) ) {
264                  }                  return $rec->{$f};
         } else {  
                 return;  
265          }          }
266  }  }
267    
268    =head2 rec2
269    
270  =head2 fill_in_to_arr  Return all values in specific field and subfield
271    
272  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]');  
273    
274  =cut  =cut
275    
276  sub fill_in_to_arr {  sub rec2 {
277          my $self = shift;          my $f = shift;
278            return unless (defined($rec && $rec->{$f}));
279            my $sf = shift;
280            return map { $_->{$sf} } grep { ref($_) eq 'HASH' && $_->{$sf} } @{ $rec->{$f} };
281    }
282    
283          my ($rec, $format_utf8) = @_;  =head2 rec
284    
285          my $log = $self->_get_logger();  syntaxtic sugar for
286    
287          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);    @v = rec('200')
288          return if (! $format_utf8);    @v = rec('200','a')
289    
290          my $i = 0;  =cut
         my @arr;  
291    
292          while (my @v = $self->fill_in($rec,$format_utf8,$i++)) {  sub rec {
293                  push @arr, @v;          if ($#_ == 0) {
294                    return rec1(@_);
295            } elsif ($#_ == 1) {
296                    return rec2(@_);
297          }          }
   
         $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  
   
         return @arr;  
298  }  }
299    
300    =head2 regex
301    
302  =head2 get_data  Apply regex to some or all values
   
 Returns value from record.  
303    
304   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.  
305    
306  =cut  =cut
307    
308  sub get_data {  sub regex {
309          my $self = shift;          my $r = shift;
310            my @out;
311          my ($rec,$f,$sf,$i,$found) = @_;          #warn "r: $r\n",Dumper(\@_);
312            foreach my $t (@_) {
313          if ($$rec->{$f}) {                  next unless ($t);
314                  return '' if (! $$rec->{$f}->[$i]);                  eval "\$t =~ $r";
315                  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 '';  
316          }          }
317            return @out;
318  }  }
319    
320    =head2 prefix
321    
322  =head2 apply_format  Prefix all values with a string
323    
324  Apply format specified in tag with C<format_name="name"> and    @v = prefix( 'my_', @v );
 C<format_delimiter=";;">.  
   
  my $text = $webpac->apply_format($format_name,$format_delimiter,$data);  
   
 Formats can contain C<lookup{...}> if you need them.  
325    
326  =cut  =cut
327    
328  sub apply_format {  sub prefix {
329          my $self = shift;          my $p = shift or die "prefix needs string as first argument";
330            return map { $p . $_ } grep { defined($_) } @_;
331          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);  
332    
333          my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'");  =head2 suffix
334    
335          my @data = split(/\Q$delimiter\E/, $data);  suffix all values with a string
336    
337          my $out = sprintf($format, @data);    @v = suffix( '_my', @v );
         $log->debug("using format $name [$format] on $data to produce: $out");  
338    
339          if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) {  =cut
                 return $self->{'lookup'}->lookup($out);  
         } else {  
                 return $out;  
         }  
340    
341    sub suffix {
342            my $s = shift or die "suffix needs string as first argument";
343            return map { $_ . $s } grep { defined($_) } @_;
344  }  }
345    
346  =head2 sort_arr  =head2 surround
347    
348  Sort array ignoring case and html in data  surround all values with a two strings
349    
350   my @sorted = $webpac->sort_arr(@unsorted);    @v = surround( 'prefix_', '_suffix', @v );
351    
352  =cut  =cut
353    
354  sub sort_arr {  sub surround {
355          my $self = shift;          my $p = shift or die "surround need prefix as first argument";
356            my $s = shift or die "surround needs suffix as second argument";
357          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;  
358  }  }
359    
360    =head2 first
361    
362  =head1 INTERNAL METHODS  Return first element
   
 =head2 _sort_by_order  
363    
364  Sort xml tags data structure accoding to C<order=""> attribute.    $v = first( @v );
365    
366  =cut  =cut
367    
368  sub _sort_by_order {  sub first {
369          my $self = shift;          my $r = shift;
370            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;  
371  }  }
372    
373  =head2 _x  =head2 lookup
374    
375  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).  
376    
377   my $text = $n->_x('normalize text string');    @v = lookup( $v );
378      @v = lookup( @v );
 This is a stub so that other modules doesn't have to implement it.  
379    
380  =cut  =cut
381    
382  sub _x {  sub lookup {
383          my $self = shift;          my $k = shift or return;
384          return shift;          return unless (defined($lookup->{$k}));
385            if (ref($lookup->{$k}) eq 'ARRAY') {
386                    return @{ $lookup->{$k} };
387            } else {
388                    return $lookup->{$k};
389            }
390  }  }
391    
392    =head2 join_with
393    
394  =head1 AUTHOR  Joins walues with some delimiter
   
 Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>  
395    
396  =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.  
397    
398  =cut  =cut
399    
400  1; # End of WebPAC::Normalize  sub join_with {
401            my $d = shift;
402            return join($d, grep { defined($_) && $_ ne '' } @_);
403    }
404    
405    # END
406    1;

Legend:
Removed from v.252  
changed lines
  Added in v.541

  ViewVC Help
Powered by ViewVC 1.1.26