/[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 540 by dpavlin, Thu Jun 29 15:29:41 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;
 use Storable;  
20    
21  =head1 NAME  =head1 NAME
22    
23  WebPAC::Normalize - data mungling for normalisation  WebPAC::Normalize - describe normalisaton rules using sets
24    
25  =head1 VERSION  =head1 VERSION
26    
27  Version 0.01  Version 0.05
28    
29  =cut  =cut
30    
31  our $VERSION = '0.01';  our $VERSION = '0.05';
32    
33  =head1 SYNOPSIS  =head1 SYNOPSIS
34    
35  This package contains code that mungle data to produce normalized format.  This module uses C<conf/normalize/*.pl> files to perform normalisation
36    from input records using perl functions which are specialized for set
37  It contains several assumptions:  processing.
38    
39  =over  Sets are implemented as arrays, and normalisation file is valid perl, which
40    means that you check it's validity before running WebPAC using
41  =item *  C<perl -c normalize.pl>.
42    
43  format of fields is defined using C<v123^a> notation for repeatable fields  Normalisation can generate multiple output normalized data. For now, supported output
44  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
45  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 *  
46    
47  optional C<filter{filter_name}> at B<begining of format> will apply perl  =head1 FUNCTIONS
 code defined as code ref on format after field substitution to producing  
 output  
48    
49  =item *  Functions which start with C<_> are private and used by WebPAC internally.
50    All other functions are available for use within normalisation rules.
51    
52  optional C<lookup{...}> will be then performed. See C<WebPAC::Lookups>.  =head2 data_structure
53    
54  =item *  Return data structure
55    
56  at end, optional C<format>s rules are resolved. Format rules are similar to    my $ds = WebPAC::Normalize::data_structure(
57  C<sprintf> and can also contain C<lookup{...}> which is performed after          lookup => $lookup->lookup_hash,
58  values are inserted in format.          row => $row,
59            rules => $normalize_pl_config,
60      );
61    
62  =back  Options C<lookup>, C<row>, C<rules> and C<log> are mandatory while all
63    other are optional.
64    
65  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.  
66    
67    Since this function isn't exported you have to call it with
68    C<WebPAC::Normalize::data_structure>.
69    
70    =cut
71    
72    sub data_structure {
73            my $arg = {@_};
74    
75  =head1 FUNCTIONS          die "need row argument" unless ($arg->{row});
76            die "need normalisation argument" unless ($arg->{rules});
77    
78  =head2 new          no strict 'subs';
79            _set_lookup( $arg->{lookup} );
80            _set_rec( $arg->{row} );
81            _clean_ds();
82    
83  Create new normalisation object          eval "$arg->{rules}";
84            die "error evaling $arg->{rules}: $@\n" if ($@);
85    
86    my $n = new WebPAC::Normalize::Something(          return _get_ds();
87          filter => {  }
                 'filter_name_1' => sub {  
                         # filter code  
                         return length($_);  
                 }, ...  
         },  
         cache_data_structure => './cache/ds/',  
         lookup_regex => $lookup->regex,  
   );  
88    
89  Parametar C<filter> defines user supplied snippets of perl code which can  =head2 _set_rec
 be use with C<filter{...}> notation.  
90    
91  Optional parameter C<cache_data_structure> defines path to directory  Set current record hash
 in which cache file for C<data_structure> call will be created.  
92    
93  Recommended parametar C<lookup_regex> is used to enable parsing of lookups    _set_rec( $rec );
 in structures.  
94    
95  =cut  =cut
96    
97  sub new {  my $rec;
         my $class = shift;  
         my $self = {@_};  
         bless($self, $class);  
   
         $self->setup_cache_dir( $self->{'cache_data_structure'} );  
98    
99          $self ? return $self : return undef;  sub _set_rec {
100            $rec = shift or die "no record hash";
101  }  }
102    
103  =head2 setup_cache_dir  =head2 _get_ds
104    
105  Check if specified cache directory exist, and if not, disable caching.  Return hash formatted as data structure
106    
107   $setup_cache_dir('./cache/ds/');    my $ds = _get_ds();
   
 If you pass false or zero value to this function, it will disable  
 cacheing.  
108    
109  =cut  =cut
110    
111  sub setup_cache_dir {  my $out;
112          my $self = shift;  my $marc21;
   
         my $dir = shift;  
   
         my $log = $self->_get_logger();  
113    
114          if ($dir) {  sub _get_ds {
115                  my $msg;          return $out;
                 if (! -e $dir) {  
                         $msg = "doesn't exist";  
                 } elsif (! -d $dir) {  
                         $msg = "is not directory";  
                 } elsif (! -w $dir) {  
                         $msg = "not writable";  
                 }  
   
                 if ($msg) {  
                         undef $self->{'cache_data_structure'};  
                         $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'};  
         }  
116  }  }
117    
118    =head2 _clean_ds
119    
120  =head2 data_structure  Clean data structure hash for next record
   
 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);  
   
 B<Note: historical oddity follows>  
121    
122  This method will also set C<< $webpac->{'currnet_filename'} >> if there is    _clean_ds();
 C<< <filename> >> tag and C<< $webpac->{'headline'} >> if there is  
 C<< <headline> >> tag.  
123    
124  =cut  =cut
125    
126  sub data_structure {  sub _clean_ds {
127          my $self = shift;          $out = undef;
128            $marc21 = undef;
129          my $log = $self->_get_logger();  }
   
         my $rec = shift;  
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
   
         my $cache_file;  
   
         if (my $cache_path = $self->{'cache_data_structure'}) {  
                 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'};  
                                         }  
                                 }  
                         }  
                 }  
         }  
   
         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 = $tag->{'value'} || $tag->{'content'};  
   
                         $log->debug("format: $format");  
   
                         my @v;  
                         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);  
   
                         if ($tag->{'sort'}) {  
                                 @v = $self->sort_arr(@v);  
                         }  
   
                         # use format?  
                         if ($tag->{'format_name'}) {  
                                 @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v;  
                         }  
   
                         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!  
                         }  
   
                         # delimiter will join repeatable fields  
                         if ($tag->{'delimiter'}) {  
                                 @v = ( join($tag->{'delimiter'}, @v) );  
                         }  
   
                         # 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;  
                                 }  
                         }  
   
   
                 }  
   
                 if ($row) {  
                         $row->{'tag'} = $field;  
130    
131                          # TODO: name_sigular, name_plural  =head2 _set_lookup
                         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");  
                         }  
132    
133                          push @ds, $row;  Set current lookup hash
134    
135                          $log->debug("row $field: ",sub { Dumper($row) });    _set_lookup( $lookup );
                 }  
136    
137          }  =cut
   
         if ($cache_file) {  
                 store {  
                         ds => \@ds,  
                         current_filename => $self->{'current_filename'},  
                         headline => $self->{'headline'},  
                 }, $cache_file;  
                 $log->debug("created storable cache file $cache_file");  
         }  
138    
139          return @ds;  my $lookup;
140    
141    sub _set_lookup {
142            $lookup = shift;
143  }  }
144    
145  =head2 parse  =head2 _get_marc21_fields
146    
147  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.  
148    
149   my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i);          $marc->add_fields( WebPAC::Normalize:_get_marc21_fields() );
150    
151  =cut  =cut
152    
153  sub parse {  sub _get_marc21_fields {
154          my $self = shift;          return @{$marc21};
155    }
         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);  
156    
157          $i = 0 if (! $i);  =head1 Functions to create C<data_structure>
158    
159          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.
160    
161          my @out;  =head2 tag
162    
163          $log->debug("format: $format");  Define new tag for I<search> and I<display>.
164    
165          my $eval_code;    tag('Title', rec('200','a') );
         # remove eval{...} from beginning  
         $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);  
166    
         my $filter_name;  
         # remove filter{...} from beginning  
         $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);  
167    
168          my $prefix;  =cut
         my $all_found=0;  
   
         while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) {  
169    
170                  my $del = $1 || '';  sub tag {
171                  $prefix ||= $del if ($all_found == 0);          my $name = shift or die "tag needs name as first argument";
172            my @o = grep { defined($_) && $_ ne '' } @_;
173            return unless (@o);
174            $out->{$name}->{tag} = $name;
175            $out->{$name}->{search} = \@o;
176            $out->{$name}->{display} = \@o;
177    }
178    
179                  # repeatable index  =head2 display
                 my $r = $i;  
                 $r = 0 if (lc("$2") eq 's');  
180    
181                  my $found = 0;  Define tag just for I<display>
                 my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found);  
182    
183                  if ($found) {    @v = display('Title', rec('200','a') );
                         push @out, $del;  
                         push @out, $tmp;  
                         $all_found += $found;  
                 }  
         }  
184    
185          return if (! $all_found);  =cut
186    
187          my $out = join('',@out);  sub display {
188            my $name = shift or die "display needs name as first argument";
189            my @o = grep { defined($_) && $_ ne '' } @_;
190            return unless (@o);
191            $out->{$name}->{tag} = $name;
192            $out->{$name}->{display} = \@o;
193    }
194    
195          if ($out) {  =head2 search
                 # add rest of format (suffix)  
                 $out .= $format;  
196    
197                  # add prefix if not there  Prepare values just for I<search>
                 $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/);  
198    
199                  $log->debug("result: $out");    @v = search('Title', rec('200','a') );
         }  
200    
201          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");  
         }  
202    
203          return $out;  sub search {
204            my $name = shift or die "search needs name as first argument";
205            my @o = grep { defined($_) && $_ ne '' } @_;
206            return unless (@o);
207            $out->{$name}->{tag} = $name;
208            $out->{$name}->{search} = \@o;
209  }  }
210    
211  =head2 parse_to_arr  =head2 marc21
212    
213  Similar to C<parse>, but returns array of all repeatable fields  Save value for MARC field
214    
215   my @arr = $webpac->parse_to_arr($rec,'v250^a');    marc21('900','a', rec('200','a') );
216    
217  =cut  =cut
218    
219  sub parse_to_arr {  sub marc21 {
220          my $self = shift;          my $f = shift or die "marc21 needs field";
221            die "marc21 field must be numer" unless ($f =~ /^\d+$/);
         my ($rec, $format_utf8) = @_;  
222    
223          my $log = $self->_get_logger();          my $sf = shift or die "marc21 needs subfield";
224    
225          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);          foreach my $v (@_) {
226          return if (! $format_utf8);                  push @{ $marc21 }, [ $f, ' ', ' ', $sf => $v ];
   
         my $i = 0;  
         my @arr;  
   
         while (my $v = $self->parse($rec,$format_utf8,$i++)) {  
                 push @arr, $v;  
227          }          }
   
         $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  
   
         return @arr;  
228  }  }
229    
230    =head1 Functions to extract data from input
231    
232  =head2 fill_in  This function should be used inside functions to create C<data_structure> described
233    above.
234    
235  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.  
236    
237   my $text = $webpac->fill_in($rec,'v250^a');  Return all values in some field
238    
239  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.  
240    
241   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.  
242    
243  =cut  =cut
244    
245  sub fill_in {  sub rec1 {
246          my $self = shift;          my $f = shift;
247            return unless (defined($rec) && defined($rec->{$f}));
248          my $log = $self->_get_logger();          if (ref($rec->{$f}) eq 'ARRAY') {
249                    return map {
250          my $rec = shift || $log->logconfess("need data record");                          if (ref($_) eq 'HASH') {
251          my $format = shift || $log->logconfess("need format to parse");                                  values %{$_};
252          # iteration (for repeatable fields)                          } else {
253          my $i = shift || 0;                                  $_;
254                            }
255          $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999));                  } @{ $rec->{$f} };
256            } elsif( defined($rec->{$f}) ) {
257          # 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;  
258          }          }
259  }  }
260    
261    =head2 rec2
262    
263  =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.  
264    
265   my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]');    @v = rec2('200','a')
266    
267  =cut  =cut
268    
269  sub fill_in_to_arr {  sub rec2 {
270          my $self = shift;          my $f = shift;
271            return unless (defined($rec && $rec->{$f}));
272            my $sf = shift;
273            return map { $_->{$sf} } grep { ref($_) eq 'HASH' && $_->{$sf} } @{ $rec->{$f} };
274    }
275    
276          my ($rec, $format_utf8) = @_;  =head2 rec
277    
278          my $log = $self->_get_logger();  syntaxtic sugar for
279    
280          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);    @v = rec('200')
281          return if (! $format_utf8);    @v = rec('200','a')
282    
283          my $i = 0;  =cut
         my @arr;  
284    
285          while (my @v = $self->fill_in($rec,$format_utf8,$i++)) {  sub rec {
286                  push @arr, @v;          if ($#_ == 0) {
287                    return rec1(@_);
288            } elsif ($#_ == 1) {
289                    return rec2(@_);
290          }          }
   
         $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  
   
         return @arr;  
291  }  }
292    
293    =head2 regex
294    
295  =head2 get_data  Apply regex to some or all values
296    
297  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.  
298    
299  =cut  =cut
300    
301  sub get_data {  sub regex {
302          my $self = shift;          my $r = shift;
303            my @out;
304          my ($rec,$f,$sf,$i,$found) = @_;          #warn "r: $r\n",Dumper(\@_);
305            foreach my $t (@_) {
306          if ($$rec->{$f}) {                  next unless ($t);
307                  return '' if (! $$rec->{$f}->[$i]);                  eval "\$t =~ $r";
308                  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 '';  
309          }          }
310            return @out;
311  }  }
312    
313    =head2 prefix
314    
315  =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);  
316    
317  Formats can contain C<lookup{...}> if you need them.    @v = prefix( 'my_', @v );
318    
319  =cut  =cut
320    
321  sub apply_format {  sub prefix {
322          my $self = shift;          my $p = shift or die "prefix needs string as first argument";
323            return map { $p . $_ } grep { defined($_) } @_;
324          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);  
325    
326          my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'");  =head2 suffix
327    
328          my @data = split(/\Q$delimiter\E/, $data);  suffix all values with a string
329    
330          my $out = sprintf($format, @data);    @v = suffix( '_my', @v );
         $log->debug("using format $name [$format] on $data to produce: $out");  
331    
332          if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) {  =cut
                 return $self->lookup($out);  
         } else {  
                 return $out;  
         }  
333    
334    sub suffix {
335            my $s = shift or die "suffix needs string as first argument";
336            return map { $_ . $s } grep { defined($_) } @_;
337  }  }
338    
339  =head2 sort_arr  =head2 surround
340    
341  Sort array ignoring case and html in data  surround all values with a two strings
342    
343   my @sorted = $webpac->sort_arr(@unsorted);    @v = surround( 'prefix_', '_suffix', @v );
344    
345  =cut  =cut
346    
347  sub sort_arr {  sub surround {
348          my $self = shift;          my $p = shift or die "surround need prefix as first argument";
349            my $s = shift or die "surround needs suffix as second argument";
350          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;  
351  }  }
352    
353    =head2 first
354    
355  =head1 INTERNAL METHODS  Return first element
356    
357  =head2 _sort_by_order    $v = first( @v );
   
 Sort xml tags data structure accoding to C<order=""> attribute.  
358    
359  =cut  =cut
360    
361  sub _sort_by_order {  sub first {
362          my $self = shift;          my $r = shift;
363            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;  
364  }  }
365    
366  =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).  
367    
368   my $text = $n->_x('normalize text string');  Consult lookup hashes for some value
369    
370  This is a stub so that other modules doesn't have to implement it.    @v = lookup( $v );
371      @v = lookup( @v );
372    
373  =cut  =cut
374    
375  sub _x {  sub lookup {
376          my $self = shift;          my $k = shift or return;
377          return shift;          return unless (defined($lookup->{$k}));
378            if (ref($lookup->{$k}) eq 'ARRAY') {
379                    return @{ $lookup->{$k} };
380            } else {
381                    return $lookup->{$k};
382            }
383  }  }
384    
385    =head2 join_with
386    
387  =head1 AUTHOR  Joins walues with some delimiter
   
 Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>  
388    
389  =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.  
390    
391  =cut  =cut
392    
393  1; # End of WebPAC::DB  sub join_with {
394            my $d = shift;
395            return join($d, grep { defined($_) && $_ ne '' } @_);
396    }
397    
398    # END
399    1;

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

  ViewVC Help
Powered by ViewVC 1.1.26