/[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 15 by dpavlin, Sun Jul 17 10:42:23 2005 UTC revision 543 by dpavlin, Thu Jun 29 21:19:08 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    
18    #use base qw/WebPAC::Common/;
19  use Data::Dumper;  use Data::Dumper;
20  use Storable;  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<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    =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',
                 }, ...  
         },  
         cache_data_structure => './cache/ds/',  
         lookup_regex => $lookup->regex,  
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  Optional parameter C<cache_data_structure> defines path to directory  This function will B<die> if normalizastion can't be evaled.
 in which cache file for C<data_structure> call will be created.  
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.  C<WebPAC::Normalize::data_structure>.
71    
72  =cut  =cut
73    
74  sub new {  sub data_structure {
75          my $class = shift;          my $arg = {@_};
         my $self = {@_};  
         bless($self, $class);  
76    
77          $self->setup_cache_dir( $self->{'cache_data_structure'} );          die "need row argument" unless ($arg->{row});
78            die "need normalisation argument" unless ($arg->{rules});
79    
80          $self ? return $self : return undef;          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  =head2 setup_cache_dir          return _get_ds();
88    }
89    
90  Check if specified cache directory exist, and if not, disable caching.  =head2 _set_rec
91    
92   $setup_cache_dir('./cache/ds/');  Set current record hash
93    
94  If you pass false or zero value to this function, it will disable    _set_rec( $rec );
 cacheing.  
95    
96  =cut  =cut
97    
98  sub setup_cache_dir {  my $rec;
         my $self = shift;  
   
         my $dir = shift;  
   
         my $log = $self->_get_logger();  
   
         if ($dir) {  
                 my $msg;  
                 if (! -e $dir) {  
                         $msg = "doesn't exist";  
                 } elsif (! -d $dir) {  
                         $msg = "is not directory";  
                 } elsif (! -w $dir) {  
                         $msg = "not writable";  
                 }  
99    
100                  if ($msg) {  sub _set_rec {
101                          undef $self->{'cache_data_structure'};          $rec = shift or die "no record hash";
                         $log->warn("cache_data_structure $dir $msg, disabling...");  
                 } else {  
                         $log->debug("using cache dir $dir");  
                 }  
         } else {  
                 $log->debug("disabling cache");  
                 undef $self->{'cache_data_structure'};  
         }  
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>.  
107    
108  This structures are used to produce output.    my $ds = _get_ds();
   
  my @ds = $webpac->data_structure($rec);  
   
 B<Note: historical oddity follows>  
   
 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;
113          my $self = shift;  my $marc21;
114    my $marc_encoding;
115    
116          my $log = $self->_get_logger();  sub _get_ds {
117            return $out;
118    }
119    
120          my $rec = shift;  =head2 _clean_ds
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
121    
122          my $cache_file;  Clean data structure hash for next record
123    
124          if (my $cache_path = $self->{'cache_data_structure'}) {    _clean_ds();
                 my $id = $rec->{'000'};  
                 $id = $rec->{'000'}->[0] if ($id =~ m/^ARRAY/o);  
                 unless (defined($id)) {  
                         $log->warn("Can't use cache_data_structure on records without unique identifier in field 000");  
                         undef $self->{'cache_data_structure'};  
                 } else {  
                         $cache_file = "$cache_path/$id";  
                         if (-r $cache_file) {  
                                 my $ds_ref = retrieve($cache_file);  
                                 if ($ds_ref) {  
                                         $log->debug("cache hit: $cache_file");  
                                         my $ok = 1;  
                                         foreach my $f (qw(current_filename headline)) {  
                                                 if ($ds_ref->{$f}) {  
                                                         $self->{$f} = $ds_ref->{$f};  
                                                 } else {  
                                                         $ok = 0;  
                                                 }  
                                         };  
                                         if ($ok && $ds_ref->{'ds'}) {  
                                                 return @{ $ds_ref->{'ds'} };  
                                         } else {  
                                                 $log->warn("cache_data_structure $cache_path corrupt. Use rm $cache_path/* to re-create it on next run!");  
                                                 undef $self->{'cache_data_structure'};  
                                         }  
                                 }  
                         }  
                 }  
         }  
125    
126          undef $self->{'currnet_filename'};  =cut
         undef $self->{'headline'};  
127    
128          my @sorted_tags;  sub _clean_ds {
129          if ($self->{tags_by_order}) {          my $a = {@_};
130                  @sorted_tags = @{$self->{tags_by_order}};          $out = undef;
131          } else {          $marc21 = undef;
132                  @sorted_tags = sort { $self->_sort_by_order } keys %{$self->{'import_xml'}->{'indexer'}};          $marc_encoding = $a->{marc_encoding};
133                  $self->{tags_by_order} = \@sorted_tags;  }
         }  
134    
135          my @ds;  =head2 _set_lookup
136    
137          $log->debug("tags: ",sub { join(", ",@sorted_tags) });  Set current lookup hash
138    
139          foreach my $field (@sorted_tags) {    _set_lookup( $lookup );
140    
141                  my $row;  =cut
142    
143  #print "field $field [",$self->{'tag'},"] = ",Dumper($self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}});  my $lookup;
144    
145                  foreach my $tag (@{$self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}}) {  sub _set_lookup {
146                          my $format = $tag->{'value'} || $tag->{'content'};          $lookup = shift;
147    }
148    
149                          $log->debug("format: $format");  =head2 _get_marc21_fields
150    
151                          my @v;  Get all fields defined by calls to C<marc21>
                         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);  
152    
153                          if ($tag->{'sort'}) {          $marc->add_fields( WebPAC::Normalize:_get_marc21_fields() );
                                 @v = $self->sort_arr(@v);  
                         }  
154    
                         # use format?  
                         if ($tag->{'format_name'}) {  
                                 @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v;  
                         }  
155    
                         if ($field eq 'filename') {  
                                 $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!  
                         }  
156    
157                          # delimiter will join repeatable fields  We are using I<magic> which detect repeatable fields only from
158                          if ($tag->{'delimiter'}) {  sequence of field/subfield data generated by normalization.
                                 @v = ( join($tag->{'delimiter'}, @v) );  
                         }  
159    
160                          # default types  Repeatable field is created if there is second occurence of same subfield or
161                          my @types = qw(display swish);  if any of indicators are different. This is sane for most cases except for
162                          # override by type attribute  non-repeatable fields with repeatable subfields.
                         @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;  
                                 }  
                         }  
163    
164    B<TODO>: implement exceptions to magic
165    
166                  }  =cut
   
                 if ($row) {  
                         $row->{'tag'} = $field;  
   
                         # TODO: name_sigular, name_plural  
                         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");  
                         }  
   
                         push @ds, $row;  
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                    ) {
177                            push @$last, ( $row->[3] , $row->[4] );
178                            warn "## ++ added $row->[0] ^$row->[3] to $last->[0]\n";
179                            next;
180                    } elsif ($last) {
181                            push @m, $last;
182                  }                  }
183    
184                    $last = $row;
185          }          }
186    
187          if ($cache_file) {          push @m, $last if ($last);
                 store {  
                         ds => \@ds,  
                         current_filename => $self->{'current_filename'},  
                         headline => $self->{'headline'},  
                 }, $cache_file;  
                 $log->debug("created storable cache file $cache_file");  
         }  
   
         return @ds;  
188    
189            return @m;
190  }  }
191    
192  =head2 parse  =head1 Functions to create C<data_structure>
   
 Perform smart parsing of string, skipping delimiters for fields which aren't  
 defined. It can also eval code in format starting with C<eval{...}> and  
 return output or nothing depending on eval code.  
   
  my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i);  
   
 =cut  
   
 sub parse {  
         my $self = shift;  
   
         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);  
   
         $i = 0 if (! $i);  
   
         my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'});  
193    
194          my @out;  Those functions generally have to first in your normalization file.
195    
196          $log->debug("format: $format");  =head2 tag
197    
198          my $eval_code;  Define new tag for I<search> and I<display>.
         # remove eval{...} from beginning  
         $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);  
199    
200          my $filter_name;    tag('Title', rec('200','a') );
         # remove filter{...} from beginning  
         $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);  
201    
         my $prefix;  
         my $all_found=0;  
202    
203          while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) {  =cut
204    
205                  my $del = $1 || '';  sub tag {
206                  $prefix ||= $del if ($all_found == 0);          my $name = shift or die "tag needs name as first argument";
207            my @o = grep { defined($_) && $_ ne '' } @_;
208            return unless (@o);
209            $out->{$name}->{tag} = $name;
210            $out->{$name}->{search} = \@o;
211            $out->{$name}->{display} = \@o;
212    }
213    
214                  # repeatable index  =head2 display
                 my $r = $i;  
                 $r = 0 if (lc("$2") eq 's');  
215    
216                  my $found = 0;  Define tag just for I<display>
                 my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found);  
217    
218                  if ($found) {    @v = display('Title', rec('200','a') );
                         push @out, $del;  
                         push @out, $tmp;  
                         $all_found += $found;  
                 }  
         }  
219    
220          return if (! $all_found);  =cut
221    
222          my $out = join('',@out);  sub display {
223            my $name = shift or die "display needs name as first argument";
224            my @o = grep { defined($_) && $_ ne '' } @_;
225            return unless (@o);
226            $out->{$name}->{tag} = $name;
227            $out->{$name}->{display} = \@o;
228    }
229    
230          if ($out) {  =head2 search
                 # add rest of format (suffix)  
                 $out .= $format;  
231    
232                  # add prefix if not there  Prepare values just for I<search>
                 $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/);  
233    
234                  $log->debug("result: $out");    @v = search('Title', rec('200','a') );
         }  
235    
236          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");  
         }  
237    
238          return $out;  sub search {
239            my $name = shift or die "search needs name as first argument";
240            my @o = grep { defined($_) && $_ ne '' } @_;
241            return unless (@o);
242            $out->{$name}->{tag} = $name;
243            $out->{$name}->{search} = \@o;
244  }  }
245    
246  =head2 parse_to_arr  =head2 marc21
247    
248  Similar to C<parse>, but returns array of all repeatable fields  Save value for MARC field
249    
250   my @arr = $webpac->parse_to_arr($rec,'v250^a');    marc21('900','a', rec('200','a') );
251    
252  =cut  =cut
253    
254  sub parse_to_arr {  sub marc21 {
255          my $self = shift;          my $f = shift or die "marc21 needs field";
256            die "marc21 field must be numer" unless ($f =~ /^\d+$/);
         my ($rec, $format_utf8) = @_;  
   
         my $log = $self->_get_logger();  
   
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
         return if (! $format_utf8);  
257    
258          my $i = 0;          my $sf = shift or die "marc21 needs subfield";
         my @arr;  
259    
260          while (my $v = $self->parse($rec,$format_utf8,$i++)) {          foreach (@_) {
261                  push @arr, $v;                  my $v = $_;             # make var read-write for Encode
262                    next unless (defined($v) && $v !~ /^\s*$/);
263                    from_to($v, 'iso-8859-2', $marc_encoding) if ($marc_encoding);
264                    push @{ $marc21 }, [ $f, ' ', ' ', $sf => $v ];
265          }          }
   
         $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  
   
         return @arr;  
266  }  }
267    
268    =head1 Functions to extract data from input
269    
270  =head2 fill_in  This function should be used inside functions to create C<data_structure> described
271    above.
 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.  
   
  my $text = $webpac->fill_in($rec,'v250^a');  
272    
273  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.  
274    
275   my $text = $webpac->fill_in($rec,'Title: v250^a',1);  Return all values in some field
276    
277  This function B<does not> perform parsing of format to inteligenty skip    @v = rec1('200')
 delimiters before fields which aren't used.  
278    
279  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.  
280    
281  =cut  =cut
282    
283  sub fill_in {  sub rec1 {
284          my $self = shift;          my $f = shift;
285            return unless (defined($rec) && defined($rec->{$f}));
286          my $log = $self->_get_logger();          if (ref($rec->{$f}) eq 'ARRAY') {
287                    return map {
288          my $rec = shift || $log->logconfess("need data record");                          if (ref($_) eq 'HASH') {
289          my $format = shift || $log->logconfess("need format to parse");                                  values %{$_};
290          # iteration (for repeatable fields)                          } else {
291          my $i = shift || 0;                                  $_;
292                            }
293          $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999));                  } @{ $rec->{$f} };
294            } elsif( defined($rec->{$f}) ) {
295          # 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;  
296          }          }
297  }  }
298    
299    =head2 rec2
300    
301  =head2 fill_in_to_arr  Return all values in specific field and subfield
   
 Similar to C<fill_in>, but returns array of all repeatable fields. Usable  
 for fields which have lookups, so they shouldn't be parsed but rather  
 C<fill_id>ed.  
302    
303   my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]');    @v = rec2('200','a')
304    
305  =cut  =cut
306    
307  sub fill_in_to_arr {  sub rec2 {
308          my $self = shift;          my $f = shift;
309            return unless (defined($rec && $rec->{$f}));
310            my $sf = shift;
311            return map { $_->{$sf} } grep { ref($_) eq 'HASH' && $_->{$sf} } @{ $rec->{$f} };
312    }
313    
314          my ($rec, $format_utf8) = @_;  =head2 rec
315    
316          my $log = $self->_get_logger();  syntaxtic sugar for
317    
318          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);    @v = rec('200')
319          return if (! $format_utf8);    @v = rec('200','a')
320    
321          my $i = 0;  =cut
         my @arr;  
322    
323          while (my @v = $self->fill_in($rec,$format_utf8,$i++)) {  sub rec {
324                  push @arr, @v;          if ($#_ == 0) {
325                    return rec1(@_);
326            } elsif ($#_ == 1) {
327                    return rec2(@_);
328          }          }
   
         $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  
   
         return @arr;  
329  }  }
330    
331    =head2 regex
332    
333  =head2 get_data  Apply regex to some or all values
334    
335  Returns value from record.    @v = regex( 's/foo/bar/g', @v );
   
  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>.  
   
 Optinal variable C<$found> will be incremeted if there  
 is field.  
   
 Returns value or empty string.  
336    
337  =cut  =cut
338    
339  sub get_data {  sub regex {
340          my $self = shift;          my $r = shift;
341            my @out;
342          my ($rec,$f,$sf,$i,$found) = @_;          #warn "r: $r\n",Dumper(\@_);
343            foreach my $t (@_) {
344          if ($$rec->{$f}) {                  next unless ($t);
345                  return '' if (! $$rec->{$f}->[$i]);                  eval "\$t =~ $r";
346                  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 '';  
347          }          }
348            return @out;
349  }  }
350    
351    =head2 prefix
352    
353  =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);  
354    
355  Formats can contain C<lookup{...}> if you need them.    @v = prefix( 'my_', @v );
356    
357  =cut  =cut
358    
359  sub apply_format {  sub prefix {
360          my $self = shift;          my $p = shift or die "prefix needs string as first argument";
361            return map { $p . $_ } grep { defined($_) } @_;
362          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);  
363    
364          my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'");  =head2 suffix
365    
366          my @data = split(/\Q$delimiter\E/, $data);  suffix all values with a string
367    
368          my $out = sprintf($format, @data);    @v = suffix( '_my', @v );
         $log->debug("using format $name [$format] on $data to produce: $out");  
369    
370          if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) {  =cut
                 return $self->lookup($out);  
         } else {  
                 return $out;  
         }  
371    
372    sub suffix {
373            my $s = shift or die "suffix needs string as first argument";
374            return map { $_ . $s } grep { defined($_) } @_;
375  }  }
376    
377  =head2 sort_arr  =head2 surround
378    
379  Sort array ignoring case and html in data  surround all values with a two strings
380    
381   my @sorted = $webpac->sort_arr(@unsorted);    @v = surround( 'prefix_', '_suffix', @v );
382    
383  =cut  =cut
384    
385  sub sort_arr {  sub surround {
386          my $self = shift;          my $p = shift or die "surround need prefix as first argument";
387            my $s = shift or die "surround needs suffix as second argument";
388          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;  
389  }  }
390    
391    =head2 first
392    
393  =head1 INTERNAL METHODS  Return first element
394    
395  =head2 _sort_by_order    $v = first( @v );
   
 Sort xml tags data structure accoding to C<order=""> attribute.  
396    
397  =cut  =cut
398    
399  sub _sort_by_order {  sub first {
400          my $self = shift;          my $r = shift;
401            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;  
402  }  }
403    
404  =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).  
405    
406   my $text = $n->_x('normalize text string');  Consult lookup hashes for some value
407    
408  This is a stub so that other modules doesn't have to implement it.    @v = lookup( $v );
409      @v = lookup( @v );
410    
411  =cut  =cut
412    
413  sub _x {  sub lookup {
414          my $self = shift;          my $k = shift or return;
415          return shift;          return unless (defined($lookup->{$k}));
416            if (ref($lookup->{$k}) eq 'ARRAY') {
417                    return @{ $lookup->{$k} };
418            } else {
419                    return $lookup->{$k};
420            }
421  }  }
422    
423    =head2 join_with
424    
425  =head1 AUTHOR  Joins walues with some delimiter
   
 Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>  
426    
427  =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.  
428    
429  =cut  =cut
430    
431  1; # End of WebPAC::DB  sub join_with {
432            my $d = shift;
433            return join($d, grep { defined($_) && $_ ne '' } @_);
434    }
435    
436    # END
437    1;

Legend:
Removed from v.15  
changed lines
  Added in v.543

  ViewVC Help
Powered by ViewVC 1.1.26