/[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 371 by dpavlin, Sun Jan 8 21:16:27 2006 UTC revision 538 by dpavlin, Thu Jun 29 15:29:19 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            rec1 rec2 rec
9            regex prefix suffix surround
10            first lookup join_with
11    /;
12    
13  use warnings;  use warnings;
14  use strict;  use strict;
15  use blib;  
16  use WebPAC::Common;  #use base qw/WebPAC::Common/;
 use base 'WebPAC::Common';  
17  use Data::Dumper;  use Data::Dumper;
18    
19  =head1 NAME  =head1 NAME
20    
21  WebPAC::Normalize - data mungling for normalisation  WebPAC::Normalize - describe normalisaton rules using sets
22    
23  =head1 VERSION  =head1 VERSION
24    
25  Version 0.08  Version 0.05
26    
27  =cut  =cut
28    
29  our $VERSION = '0.08';  our $VERSION = '0.05';
30    
31  =head1 SYNOPSIS  =head1 SYNOPSIS
32    
33  This package contains code that mungle data to produce normalized format.  This module uses C<conf/normalize/*.pl> files to perform normalisation
34    from input records using perl functions which are specialized for set
35  It contains several assumptions:  processing.
36    
37  =over  Sets are implemented as arrays, and normalisation file is valid perl, which
38    means that you check it's validity before running WebPAC using
39  =item *  C<perl -c normalize.pl>.
   
 format of fields is defined using C<v123^a> notation for repeatable fields  
 or C<s123^a> for single (or first) value, where C<123> is field number and  
 C<a> is subfield.  
   
 =item *  
   
 source data records (C<$rec>) have unique identifiers in field C<000>  
   
 =item *  
   
 optional C<eval{length('v123^a') == 3}> tag at B<beginning of format> will be  
 perl code that is evaluated before producing output (value of field will be  
 interpolated before that)  
   
 =item *  
   
 optional C<filter{filter_name}> at B<begining of format> will apply perl  
 code defined as code ref on format after field substitution to producing  
 output  
   
 There is one built-in filter called C<regex> which can be use like this:  
   
   filter{regex(s/foo/bar/)}  
   
 =item *  
   
 optional C<lookup{...}> will be then performed. See C<WebPAC::Lookups>.  
   
 =item *  
   
 at end, optional C<format>s rules are resolved. Format rules are similar to  
 C<sprintf> and can also contain C<lookup{...}> which is performed after  
 values are inserted in format.  
   
 =back  
   
 This also describes order in which transformations are applied (eval,  
 filter, lookup, format) which is important to undestand when deciding how to  
 solve your data mungling and normalisation process.  
   
   
40    
41    Normalisation can generate multiple output normalized data. For now, supported output
42    types (on the left side of definition) are: C<tag>, C<display> and C<search>.
43    
44  =head1 FUNCTIONS  =head1 FUNCTIONS
45    
46  =head2 new  Functions which start with C<_> are private and used by WebPAC internally.
47    All other functions are available for use within normalisation rules.
48    
49  Create new normalisation object  =head2 data_structure
50    
51    my $n = new WebPAC::Normalize::Something(  Return data structure
         filter => {  
                 'filter_name_1' => sub {  
                         # filter code  
                         return length($_);  
                 }, ...  
         },  
         db => $db_obj,  
         lookup_regex => $lookup->regex,  
         lookup => $lookup_obj,  
         prefix => 'foobar',  
   );  
52    
53  Parametar C<filter> defines user supplied snippets of perl code which can    my $ds = WebPAC::Normalize::data_structure(
54  be use with C<filter{...}> notation.          lookup => $lookup->lookup_hash,
55            row => $row,
56            rules => $normalize_pl_config,
57      );
58    
59  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).  
60    
61  Recommended parametar C<lookup_regex> is used to enable parsing of lookups  Since this function isn't exported you have to call it with
62  in structures. If you pass this parametar, you must also pass C<lookup>  C<WebPAC::Normalize::data_structure>.
 which is C<WebPAC::Lookup> object.  
63    
64  =cut  =cut
65    
66  sub new {  sub data_structure {
67          my $class = shift;          my $arg = {@_};
         my $self = {@_};  
         bless($self, $class);  
   
         my $r = $self->{'lookup_regex'} ? 1 : 0;  
         my $l = $self->{'lookup'} ? 1 : 0;  
   
         my $log = $self->_get_logger();  
   
         # those two must be in pair  
         if ( ($r & $l) != ($r || $l) ) {  
                 my $log = $self->_get_logger();  
                 $log->logdie("lookup_regex and lookup must be in pair");  
         }  
   
         $log->logdie("lookup must be WebPAC::Lookup object") if ($self->{'lookup'} && ! $self->{'lookup'}->isa('WebPAC::Lookup'));  
   
         $log->warn("no prefix defined. please check that!") unless ($self->{'prefix'});  
   
         $log->debug("using lookup regex: ", $self->{lookup_regex}) if ($r && $l);  
68    
69          if (! $self->{filter} || ! $self->{filter}->{regex}) {          die "need row argument" unless ($arg->{row});
70                  $log->debug("adding built-in filter regex");          die "need normalisation argument" unless ($arg->{rules});
                 $self->{filter}->{regex} = sub {  
                         my ($val, $regex) = @_;  
                         eval "\$val =~ $regex";  
                         return $val;  
                 };  
         }  
71    
72          $self ? return $self : return undef;          no strict 'subs';
73            _set_lookup( $arg->{lookup} );
74            _set_rec( $arg->{row} );
75            _clean_ds();
76            eval "$arg->{rules}";
77            die "error evaling $arg->{rules}: $@\n" if ($@);
78            return _get_ds();
79  }  }
80    
81    =head2 _set_rec
82    
83  =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.  
84    
85   my $ds = $webpac->data_structure($rec);    _set_rec( $rec );
86    
87  =cut  =cut
88    
89  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) });  
   
         $log->logdie("need unique ID (mfn) in field 000 of record " . Dumper($rec) ) unless (defined($rec->{'000'}));  
   
         my $id = $rec->{'000'}->[0] || $log->logdie("field 000 isn't array!");  
   
         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");  
         }  
   
         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;  
   
                         $log->logdie("expected tag HASH and got $tag") unless (ref($tag) eq 'HASH');  
                         $format = $tag->{'value'} || $tag->{'content'};  
   
                         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);  
                         }  
                         if (! @v) {  
                                 $log->debug("$field <",$self->{tag},"> format: $format no values");  
 #                               next;  
                         } else {  
                                 $log->debug("$field <",$self->{tag},"> format: $format values: ", join(",", @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;  
                         }  
   
                         # 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("tag $field / $type [",sub { join(",",@v) }, "] ", $row->{'append'} || 'no append');  
                                 if ($tag->{'append'}) {  
   
                                         # I will delimit appended part with  
                                         # delimiter (or ,)  
                                         my $d = $tag->{'delimiter'};  
                                         # default delimiter  
                                         $d ||= " ";  
   
                                         my $last = pop @{$row->{$type}};  
                                         $d = "" if (! $last);  
                                         $last .= $d . join($d, @v);  
                                         push @{$row->{$type}}, $last;  
   
                                 } else {  
                                         push @{$row->{$type}}, @v;  
                                 }  
                         }  
   
   
                 }  
   
                 if ($row) {  
                         $row->{'tag'} = $field;  
   
                         # TODO: name_sigular, name_plural  
                         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");  
                         }  
   
                         $ds->{$row_name} = $row;  
   
                         $log->debug("row $field: ",sub { Dumper($row) });  
                 }  
   
         }  
   
         $self->{'db'}->save_ds(  
                 id => $id,  
                 ds => $ds,  
                 prefix => $self->{prefix},  
         ) if ($self->{'db'});  
   
         $log->debug("ds: ", sub { Dumper($ds) });  
   
         $log->logconfess("data structure returned is not array any more!") if wantarray;  
   
         return $ds;  
90    
91    sub _set_rec {
92            $rec = shift or die "no record hash";
93  }  }
94    
95  =head2 parse  =head2 _get_ds
   
 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);  
   
 Filters are implemented here. While simple form of filters looks like this:  
96    
97    filter{name_of_filter}  Return hash formatted as data structure
98    
99  but, filters can also have variable number of parametars like this:    my $ds = _get_ds();
   
   filter{name_of_filter(param,param,param)}  
100    
101  =cut  =cut
102    
103  my $warn_once;  my $out;
   
 sub parse {  
         my $self = shift;  
   
         my ($rec, $format_utf8, $i, $rec_size) = @_;  
   
         return if (! $format_utf8);  
   
         my $log = $self->_get_logger();  
   
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
   
         $i = 0 if (! $i);  
   
         my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'});  
   
         my @out;  
   
         $log->debug("format: $format [$i]");  
   
         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);  
   
         # did we found any (att all) field from format in row?  
         my $found_any;  
         # prefix before first field which we preserve it $found_any  
         my $prefix;  
   
         my $f_step = 1;  
   
         while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) {  
   
                 my $del = $1 || '';  
                 $prefix = $del if ($f_step == 1);  
   
                 my $fld_type = lc($2);  
   
                 # repeatable index  
                 my $r = $i;  
                 if ($fld_type eq 's') {  
                         if ($found_any->{'v'}) {  
                                 $r = 0;  
                         } else {  
                                 return;  
                         }  
                 }  
   
                 my $found = 0;  
                 my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found,$rec_size);  
   
                 if ($found) {  
                         $found_any->{$fld_type} += $found;  
   
                         # we will skip delimiter before first occurence of field!  
                         push @out, $del unless($found_any->{$fld_type} == 1);  
                         push @out, $tmp;  
                 }  
                 $f_step++;  
         }  
   
         # test if any fields found?  
         return if (! $found_any->{'v'} && ! $found_any->{'s'});  
   
         my $out = join('',@out);  
   
         if ($out) {  
                 # add rest of format (suffix)  
                 $out .= $format;  
   
                 # add prefix if not there  
                 $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/);  
   
                 $log->debug("result: $out");  
         }  
   
         if ($eval_code) {  
                 my $eval = $self->fill_in($rec,$eval_code,$i) || return;  
                 $log->debug("about to eval{$eval} format: $out");  
                 return if (! $self->_eval($eval));  
         }  
           
         if ($filter_name) {  
                 my @filter_args;  
                 if ($filter_name =~ s/(\w+)\((.*)\)/$1/) {  
                         @filter_args = split(/,/, $2);  
                 }  
                 if ($self->{'filter'}->{$filter_name}) {  
                         $log->debug("about to filter{$filter_name} format: $out with arguments: ", join(",", @filter_args));  
                         unshift @filter_args, $out;  
                         $out = $self->{'filter'}->{$filter_name}->(@filter_args);  
                         return unless(defined($out));  
                         $log->debug("filter result: $out");  
                 } elsif (! $warn_once->{$filter_name}) {  
                         $log->warn("trying to use undefined filter $filter_name");  
                         $warn_once->{$filter_name}++;  
                 }  
         }  
104    
105    sub _get_ds {
106          return $out;          return $out;
107  }  }
108    
109  =head2 parse_to_arr  =head2 _clean_ds
110    
111  Similar to C<parse>, but returns array of all repeatable fields  Clean data structure hash for next record
112    
113   my @arr = $webpac->parse_to_arr($rec,'v250^a');    _clean_ds();
114    
115  =cut  =cut
116    
117  sub parse_to_arr {  sub _clean_ds {
118          my $self = shift;          $out = undef;
119    }
         my ($rec, $format_utf8) = @_;  
   
         my $log = $self->_get_logger();  
120    
121          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  =head2 _set_lookup
         return if (! $format_utf8);  
122    
123          my $i = 0;  Set current lookup hash
         my @arr;  
124    
125          my $rec_size = { '_' => '_' };    _set_lookup( $lookup );
126    
127          while (my $v = $self->parse($rec,$format_utf8,$i++,\$rec_size)) {  =cut
                 push @arr, $v;  
                 warn "parse rec_size = ", Dumper($rec_size);  
         }  
128    
129          $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  my $lookup;
130    
131          return @arr;  sub _set_lookup {
132            $lookup = shift;
133  }  }
134    
135    =head2 tag
136    
137  =head2 fill_in  Define new tag for I<search> and I<display>.
138    
139  Workhourse of all: takes record from in-memory structure of database and    tag('Title', rec('200','a') );
 strings with placeholders and returns string or array of with substituted  
 values from record.  
140    
  my $text = $webpac->fill_in($rec,'v250^a');  
141    
142  Optional argument is ordinal number for repeatable fields. By default,  =cut
 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.  
   
  my $text = $webpac->fill_in($rec,'Title: v250^a',1);  
143    
144  This function B<does not> perform parsing of format to inteligenty skip  sub tag {
145  delimiters before fields which aren't used.          my $name = shift or die "tag needs name as first argument";
146            my @o = grep { defined($_) && $_ ne '' } @_;
147            return unless (@o);
148            $out->{$name}->{tag} = $name;
149            $out->{$name}->{search} = \@o;
150            $out->{$name}->{display} = \@o;
151    }
152    
153  This method will automatically decode UTF-8 string to local code page  =head2 display
 if needed.  
154    
155  There is optional parametar C<$record_size> which can be used to get sizes of  Define tag just for I<display>
 all C<field^subfield> combinations in this format.  
156    
157   my $text = $webpac->fill_in($rec,'got: v900^a v900^x',0,\$rec_size);    @v = display('Title', rec('200','a') );
158    
159  =cut  =cut
160    
161  sub fill_in {  sub display {
162          my $self = shift;          my $name = shift or die "display needs name as first argument";
163            my @o = grep { defined($_) && $_ ne '' } @_;
164            return unless (@o);
165            $out->{$name}->{tag} = $name;
166            $out->{$name}->{display} = \@o;
167    }
168    
169          my $log = $self->_get_logger();  =head2 search
170    
171          my ($rec,$format,$i,$rec_size) = @_;  Prepare values just for I<search>
172    
173          $log->logconfess("need data record") unless ($rec);    @v = search('Title', rec('200','a') );
         $log->logconfess("need format to parse") unless($format);  
174    
175          # iteration (for repeatable fields)  =cut
         $i ||= 0;  
176    
177          $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999));  sub search {
178            my $name = shift or die "search needs name as first argument";
179            my @o = grep { defined($_) && $_ ne '' } @_;
180            return unless (@o);
181            $out->{$name}->{tag} = $name;
182            $out->{$name}->{search} = \@o;
183    }
184    
185          # FIXME remove for speedup?  =head2 rec1
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
186    
187          if (utf8::is_utf8($format)) {  Return all values in some field
                 $format = $self->_x($format);  
         }  
188    
189          my $found = 0;    @v = rec1('200')
         my $just_single = 1;  
190    
191          my $eval_code;  TODO: order of values is probably same as in source data, need to investigate that
         # 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  
         if ($format =~ s/v(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,$i,\$found,$rec_size)/ges) {  
                 $just_single = 0;  
         }  
192    
193          # non-repeatable fields  =cut
         if ($format =~ s/s(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,0,\$found,$rec_size)/ges) {  
                 return if ($i > 0 && $just_single);  
         }  
194    
195          if ($found) {  sub rec1 {
196                  $log->debug("format: $format");          my $f = shift;
197                  if ($eval_code) {          return unless (defined($rec) && defined($rec->{$f}));
198                          my $eval = $self->fill_in($rec,$eval_code,$i);          if (ref($rec->{$f}) eq 'ARRAY') {
199                          return if (! $self->_eval($eval));                  return map {
200                  }                          if (ref($_) eq 'HASH') {
201                  if ($filter_name && $self->{'filter'}->{$filter_name}) {                                  values %{$_};
                         $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;  
202                          } else {                          } else {
203                                  $log->warn("Have lookup object but can't invoke lookup method");                                  $_;
204                          }                          }
205                  } else {                  } @{ $rec->{$f} };
206                          return $format;          } elsif( defined($rec->{$f}) ) {
207                  }                  return $rec->{$f};
         } else {  
                 return;  
208          }          }
209  }  }
210    
211    =head2 rec2
212    
213  =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.  
214    
215   my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]');    @v = rec2('200','a')
216    
217  =cut  =cut
218    
219  sub fill_in_to_arr {  sub rec2 {
220          my $self = shift;          my $f = shift;
221            return unless (defined($rec && $rec->{$f}));
222          my ($rec, $format_utf8) = @_;          my $sf = shift;
223            return map { $_->{$sf} } grep { ref($_) eq 'HASH' && $_->{$sf} } @{ $rec->{$f} };
224    }
225    
226          my $log = $self->_get_logger();  =head2 rec
227    
228          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  syntaxtic sugar for
         return if (! $format_utf8);  
229    
230          my $i = 0;    @v = rec('200')
231          my @arr;    @v = rec('200','a')
232    
233          my $rec_size;  =cut
234    
235          while (my $v = $self->fill_in($rec,$format_utf8,$i,\$rec_size)) {  sub rec {
236                  push @arr, $v;          if ($#_ == 0) {
237                  warn "rec_size = ", Dumper($rec_size);                  return rec1(@_);
238            } elsif ($#_ == 1) {
239                    return rec2(@_);
240          }          }
   
         $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  
   
         return @arr;  
241  }  }
242    
243    =head2 regex
244    
245  =head2 get_data  Apply regex to some or all values
   
 Returns value from record.  
   
  my $text = $self->get_data(\$rec,$f,$sf,$i,\$found,\$rec_size);  
   
 Required arguments are:  
   
 =over 8  
246    
247  =item C<$rec>    @v = regex( 's/foo/bar/g', @v );
   
 record reference  
   
 =item C<$f>  
   
 field  
   
 =item C<$sf>  
   
 optional subfield  
   
 =item C<$i>  
   
 index offset for repeatable values ( 0 ... $rec_size->{'400^a'} )  
   
 =item C<$found>  
   
 optional variable that will be incremeted if preset  
   
 =item C<$rec_size>  
   
 hash to hold maximum occurances of C<field^subfield> combinations  
 (which can be accessed using keys in same format)  
   
 =back  
   
 Returns value or empty string, updates C<$found> and C<rec_size>  
 if present.  
248    
249  =cut  =cut
250    
251  sub get_data {  sub regex {
252          my $self = shift;          my $r = shift;
253            my @out;
254          my ($rec,$f,$sf,$i,$found,$cache) = @_;          #warn "r: $r\n",Dumper(\@_);
255            foreach my $t (@_) {
256          return '' unless ($$rec->{$f} && ref($$rec->{$f}) eq 'ARRAY');                  next unless ($t);
257                    eval "\$t =~ $r";
258          if (defined($$cache)) {                  push @out, $t if ($t && $t ne '');
                 $$cache->{ $f . ( $sf ? '^' . $sf : '' ) } ||= scalar @{ $$rec->{$f} };  
         }  
   
         return '' unless ($$rec->{$f}->[$i]);  
   
         {  
                 no strict 'refs';  
                 if (defined($sf)) {  
                         $$found++ if (defined($$found) && $$rec->{$f}->[$i]->{$sf});  
                         return $$rec->{$f}->[$i]->{$sf};  
                 } else {  
                         $$found++ if (defined($$found));  
                         # it still might have subfields, just  
                         # not specified, so we'll dump some debug info  
                         if ($$rec->{$f}->[$i] =~ /HASH/o) {  
                                 my $out;  
                                 foreach my $k (keys %{$$rec->{$f}->[$i]}) {  
                                         $out .= '$' . $k .':' . $$rec->{$f}->[$i]->{$k}." ";  
                                 }  
                                 return $out;  
                         } else {  
                                 return $$rec->{$f}->[$i];  
                         }  
                 }  
259          }          }
260            return @out;
261  }  }
262    
263    =head2 prefix
264    
265  =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);  
266    
267  Formats can contain C<lookup{...}> if you need them.    @v = prefix( 'my_', @v );
268    
269  =cut  =cut
270    
271  sub apply_format {  sub prefix {
272          my $self = shift;          my $p = shift or die "prefix needs string as first argument";
273            return map { $p . $_ } grep { defined($_) } @_;
274          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);  
275    
276          my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'");  =head2 suffix
277    
278          my @data = split(/\Q$delimiter\E/, $data);  suffix all values with a string
279    
280          my $out = sprintf($format, @data);    @v = suffix( '_my', @v );
         $log->debug("using format $name [$format] on $data to produce: $out");  
281    
282          if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) {  =cut
                 return $self->{'lookup'}->lookup($out);  
         } else {  
                 return $out;  
         }  
283    
284    sub suffix {
285            my $s = shift or die "suffix needs string as first argument";
286            return map { $_ . $s } grep { defined($_) } @_;
287  }  }
288    
289  =head2 sort_arr  =head2 surround
290    
291  Sort array ignoring case and html in data  surround all values with a two strings
292    
293   my @sorted = $webpac->sort_arr(@unsorted);    @v = surround( 'prefix_', '_suffix', @v );
294    
295  =cut  =cut
296    
297  sub sort_arr {  sub surround {
298          my $self = shift;          my $p = shift or die "surround need prefix as first argument";
299            my $s = shift or die "surround needs suffix as second argument";
300          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;  
301  }  }
302    
303    =head2 first
304    
305  =head1 INTERNAL METHODS  Return first element
   
 =head2 _sort_by_order  
306    
307  Sort xml tags data structure accoding to C<order=""> attribute.    $v = first( @v );
308    
309  =cut  =cut
310    
311  sub _sort_by_order {  sub first {
312          my $self = shift;          my $r = shift;
313            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;  
314  }  }
315    
316  =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).  
317    
318   my $text = $n->_x('normalize text string');  Consult lookup hashes for some value
319    
320  This is a stub so that other modules doesn't have to implement it.    @v = lookup( $v );
321      @v = lookup( @v );
322    
323  =cut  =cut
324    
325  sub _x {  sub lookup {
326          my $self = shift;          my $k = shift or return;
327          return shift;          return unless (defined($lookup->{$k}));
328            if (ref($lookup->{$k}) eq 'ARRAY') {
329                    return @{ $lookup->{$k} };
330            } else {
331                    return $lookup->{$k};
332            }
333  }  }
334    
335    =head2 join_with
336    
337  =head1 AUTHOR  Joins walues with some delimiter
   
 Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>  
   
 =head1 COPYRIGHT & LICENSE  
338    
339  Copyright 2005 Dobrica Pavlinusic, All Rights Reserved.    $v = join_with(", ", @v);
   
 This program is free software; you can redistribute it and/or modify it  
 under the same terms as Perl itself.  
340    
341  =cut  =cut
342    
343  1; # End of WebPAC::Normalize  sub join_with {
344            my $d = shift;
345            return join($d, grep { defined($_) && $_ ne '' } @_);
346    }
347    
348    # END
349    1;

Legend:
Removed from v.371  
changed lines
  Added in v.538

  ViewVC Help
Powered by ViewVC 1.1.26