/[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 721 by dpavlin, Fri Sep 29 12:27:47 2006 UTC revision 983 by dpavlin, Sun Nov 4 11:12:38 2007 UTC
# Line 1  Line 1 
1  package WebPAC::Normalize;  package WebPAC::Normalize;
2  use Exporter 'import';  use Exporter 'import';
3  @EXPORT = qw/  our @EXPORT = qw/
4          _set_rec _set_lookup          _set_ds _set_lookup
5            get_ds
6            _set_load_row
7          _get_ds _clean_ds          _get_ds _clean_ds
8          _debug          _debug
9          _pack_subfields_hash          _pack_subfields_hash
10    
11          tag search display          search_display search display sorted
12    
13          marc marc_indicators marc_repeatable_subfield          marc marc_indicators marc_repeatable_subfield
14          marc_compose marc_leader          marc_compose marc_leader marc_fixed
15          marc_duplicate marc_remove          marc_duplicate marc_remove marc_count
16          marc_original_order          marc_original_order
17    
18          rec1 rec2 rec          rec1 rec2 rec
19            frec
20          regex prefix suffix surround          regex prefix suffix surround
21          first lookup join_with          first lookup join_with
22          save_into_lookup          save_into_lookup
23    
24          split_rec_on          split_rec_on
25    
26            get set
27            count
28    
29  /;  /;
30    
31  use warnings;  use warnings;
# Line 26  use strict; Line 34  use strict;
34  #use base qw/WebPAC::Common/;  #use base qw/WebPAC::Common/;
35  use Data::Dump qw/dump/;  use Data::Dump qw/dump/;
36  use Storable qw/dclone/;  use Storable qw/dclone/;
37    use Carp qw/confess/;
38    
39  # debugging warn(s)  # debugging warn(s)
40  my $debug = 0;  my $debug = 0;
41    
42    use WebPAC::Normalize::ISBN;
43    push @EXPORT, ( 'isbn_10', 'isbn_13' );
44    
45  =head1 NAME  =head1 NAME
46    
47  WebPAC::Normalize - describe normalisaton rules using sets  WebPAC::Normalize - describe normalisaton rules using sets
48    
 =head1 VERSION  
   
 Version 0.20  
   
49  =cut  =cut
50    
51  our $VERSION = '0.20';  our $VERSION = '0.32';
52    
53  =head1 SYNOPSIS  =head1 SYNOPSIS
54    
# Line 54  means that you check it's validity befor Line 61  means that you check it's validity befor
61  C<perl -c normalize.pl>.  C<perl -c normalize.pl>.
62    
63  Normalisation can generate multiple output normalized data. For now, supported output  Normalisation can generate multiple output normalized data. For now, supported output
64  types (on the left side of definition) are: C<tag>, C<display>, C<search> and  types (on the left side of definition) are: C<search_display>, C<display>, C<search> and
65  C<marc>.  C<marc>.
66    
67  =head1 FUNCTIONS  =head1 FUNCTIONS
# Line 67  All other functions are available for us Line 74  All other functions are available for us
74  Return data structure  Return data structure
75    
76    my $ds = WebPAC::Normalize::data_structure(    my $ds = WebPAC::Normalize::data_structure(
77          lookup => $lookup_variable,          lookup => $lookup_hash,
78          row => $row,          row => $row,
79          rules => $normalize_pl_config,          rules => $normalize_pl_config,
80          marc_encoding => 'utf-8',          marc_encoding => 'utf-8',
81          config => $config,          config => $config,
82            load_row_coderef => sub {
83                    my ($database,$input,$mfn) = @_;
84                    $store->load_row( database => $database, input => $input, id => $mfn );
85            },
86    );    );
87    
88  Options C<row>, C<rules> and C<log> are mandatory while all  Options C<row>, C<rules> and C<log> are mandatory while all
89  other are optional.  other are optional.
90    
91    C<load_row_coderef> is closure only used when executing lookups, so they will
92    die if it's not defined.
93    
94  This function will B<die> if normalizastion can't be evaled.  This function will B<die> if normalizastion can't be evaled.
95    
96  Since this function isn't exported you have to call it with  Since this function isn't exported you have to call it with
# Line 84  C<WebPAC::Normalize::data_structure>. Line 98  C<WebPAC::Normalize::data_structure>.
98    
99  =cut  =cut
100    
101    my $load_row_coderef;
102    
103  sub data_structure {  sub data_structure {
104          my $arg = {@_};          my $arg = {@_};
105    
# Line 91  sub data_structure { Line 107  sub data_structure {
107          die "need normalisation argument" unless ($arg->{rules});          die "need normalisation argument" unless ($arg->{rules});
108    
109          no strict 'subs';          no strict 'subs';
110          _set_lookup( $arg->{lookup} ) if (defined( $arg->{lookup} ));          _set_lookup( $arg->{lookup} ) if defined($arg->{lookup});
111          _set_rec( $arg->{row} );          _set_ds( $arg->{row} );
112          _set_config( $arg->{config} ) if (defined( $arg->{config} ));          _set_config( $arg->{config} ) if defined($arg->{config});
113          _clean_ds( %{ $arg } );          _clean_ds( %{ $arg } );
114            $load_row_coderef = $arg->{load_row_coderef};
115    
116          eval "$arg->{rules}";          eval "$arg->{rules}";
117          die "error evaling $arg->{rules}: $@\n" if ($@);          die "error evaling $arg->{rules}: $@\n" if ($@);
118    
119          return _get_ds();          return _get_ds();
120  }  }
121    
122  =head2 _set_rec  =head2 _set_ds
123    
124  Set current record hash  Set current record hash
125    
126    _set_rec( $rec );    _set_ds( $rec );
127    
128  =cut  =cut
129    
130  my $rec;  my $rec;
131    
132  sub _set_rec {  sub _set_ds {
133          $rec = shift or die "no record hash";          $rec = shift or die "no record hash";
134  }  }
135    
136    =head2 get_ds
137    
138    Access to original record from input module
139    
140      my $ds = get_rec;
141    
142    =cut
143    
144    sub get_ds {
145            return $rec;
146    }
147    
148  =head2 _set_config  =head2 _set_config
149    
150  Set current config hash  Set current config hash
# Line 151  Return hash formatted as data structure Line 181  Return hash formatted as data structure
181    
182  =cut  =cut
183    
184  my ($out, $marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators);  my ($out, $marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators, $marc_leader);
185  my ($marc_record_offset, $marc_fetch_offset) = (0, 0);  my ($marc_record_offset, $marc_fetch_offset) = (0, 0);
186    
187  sub _get_ds {  sub _get_ds {
188    #warn "## out = ",dump($out);
189          return $out;          return $out;
190  }  }
191    
# Line 168  Clean data structure hash for next recor Line 199  Clean data structure hash for next recor
199    
200  sub _clean_ds {  sub _clean_ds {
201          my $a = {@_};          my $a = {@_};
202          ($out,$marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators) = ();          ($out,$marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators, $marc_leader) = ();
203          ($marc_record_offset, $marc_fetch_offset) = (0,0);          ($marc_record_offset, $marc_fetch_offset) = (0,0);
204          $marc_encoding = $a->{marc_encoding};          $marc_encoding = $a->{marc_encoding};
205  }  }
# Line 199  sub _get_lookup { Line 230  sub _get_lookup {
230          return $lookup;          return $lookup;
231  }  }
232    
233    =head2 _set_load_row
234    
235    Setup code reference which will return L<data_structure> from
236    L<WebPAC::Store>
237    
238      _set_load_row(sub {
239                    my ($database,$input,$mfn) = @_;
240                    $store->load_row( database => $database, input => $input, id => $mfn );
241      });
242    
243    =cut
244    
245    sub _set_load_row {
246            my $coderef = shift;
247            confess "argument isn't CODE" unless ref($coderef) eq 'CODE';
248    
249            $load_row_coderef = $coderef;
250    }
251    
252  =head2 _get_marc_fields  =head2 _get_marc_fields
253    
254  Get all fields defined by calls to C<marc>  Get all fields defined by calls to C<marc>
# Line 254  will return 42th copy record (if it exis Line 304  will return 42th copy record (if it exis
304    
305  =cut  =cut
306    
307    my $fetch_pos;
308    
309  sub _get_marc_fields {  sub _get_marc_fields {
310    
311          my $arg = {@_};          my $arg = {@_};
312          warn "### _get_marc_fields arg: ", dump($arg), $/ if ($debug > 2);          warn "### _get_marc_fields arg: ", dump($arg), $/ if ($debug > 2);
313          my $offset = $marc_fetch_offset;          $fetch_pos = $marc_fetch_offset;
314          if ($arg->{offset}) {          if ($arg->{offset}) {
315                  $offset = $arg->{offset};                  $fetch_pos = $arg->{offset};
316          } elsif($arg->{fetch_next}) {          } elsif($arg->{fetch_next}) {
317                  $marc_fetch_offset++;                  $marc_fetch_offset++;
318          }          }
# Line 269  sub _get_marc_fields { Line 321  sub _get_marc_fields {
321    
322          warn "### full marc_record = ", dump( @{ $marc_record }), $/ if ($debug > 2);          warn "### full marc_record = ", dump( @{ $marc_record }), $/ if ($debug > 2);
323    
324          my $marc_rec = $marc_record->[ $offset ];          my $marc_rec = $marc_record->[ $fetch_pos ];
325    
326          warn "## _get_marc_fields (at offset: $offset) -- marc_record = ", dump( @$marc_rec ), $/ if ($debug > 1);          warn "## _get_marc_fields (at offset: $fetch_pos) -- marc_record = ", dump( @$marc_rec ), $/ if ($debug > 1);
327    
328          return if (! $marc_rec || ref($marc_rec) ne 'ARRAY' || $#{ $marc_rec } < 0);          return if (! $marc_rec || ref($marc_rec) ne 'ARRAY' || $#{ $marc_rec } < 0);
329    
# Line 292  sub _get_marc_fields { Line 344  sub _get_marc_fields {
344    
345          if ($debug) {          if ($debug) {
346                  warn "## marc_repeatable_subfield = ", dump( $marc_repeatable_subfield ), $/ if ( $marc_repeatable_subfield );                  warn "## marc_repeatable_subfield = ", dump( $marc_repeatable_subfield ), $/ if ( $marc_repeatable_subfield );
347                  warn "## marc_record[$offset] = ", dump( $marc_rec ), $/;                  warn "## marc_record[$fetch_pos] = ", dump( $marc_rec ), $/;
348                  warn "## sorted_marc_record = ", dump( \@sorted_marc_record ), $/;                  warn "## sorted_marc_record = ", dump( \@sorted_marc_record ), $/;
349                  warn "## subfield count = ", dump( $u ), $/;                  warn "## subfield count = ", dump( $u ), $/;
350          }          }
# Line 373  sub _get_marc_fields { Line 425  sub _get_marc_fields {
425          return \@m;          return \@m;
426  }  }
427    
428    =head2 _get_marc_leader
429    
430    Return leader from currently fetched record by L</_get_marc_fields>
431    
432      print WebPAC::Normalize::_get_marc_leader();
433    
434    =cut
435    
436    sub _get_marc_leader {
437            die "no fetch_pos, did you called _get_marc_fields first?" unless ( defined( $fetch_pos ) );
438            return $marc_leader->[ $fetch_pos ];
439    }
440    
441  =head2 _debug  =head2 _debug
442    
443  Change level of debug warnings  Change level of debug warnings
# Line 392  sub _debug { Line 457  sub _debug {
457    
458  Those functions generally have to first in your normalization file.  Those functions generally have to first in your normalization file.
459    
460  =head2 tag  =head2 search_display
461    
462  Define new tag for I<search> and I<display>.  Define output for L<search> and L<display> at the same time
463    
464    tag('Title', rec('200','a') );    search_display('Title', rec('200','a') );
465    
466    
467  =cut  =cut
468    
469  sub tag {  sub search_display {
470          my $name = shift or die "tag needs name as first argument";          my $name = shift or die "search_display needs name as first argument";
471          my @o = grep { defined($_) && $_ ne '' } @_;          my @o = grep { defined($_) && $_ ne '' } @_;
472          return unless (@o);          return unless (@o);
         $out->{$name}->{tag} = $name;  
473          $out->{$name}->{search} = \@o;          $out->{$name}->{search} = \@o;
474          $out->{$name}->{display} = \@o;          $out->{$name}->{display} = \@o;
475  }  }
476    
477    =head2 tag
478    
479    Old name for L<search_display>, but supported
480    
481    =cut
482    
483    sub tag {
484            search_display( @_ );
485    }
486    
487  =head2 display  =head2 display
488    
489  Define tag just for I<display>  Define output just for I<display>
490    
491    @v = display('Title', rec('200','a') );    @v = display('Title', rec('200','a') );
492    
493  =cut  =cut
494    
495  sub display {  sub _field {
496          my $name = shift or die "display needs name as first argument";          my $type = shift or confess "need type -- BUG?";
497            my $name = shift or confess "needs name as first argument";
498          my @o = grep { defined($_) && $_ ne '' } @_;          my @o = grep { defined($_) && $_ ne '' } @_;
499          return unless (@o);          return unless (@o);
500          $out->{$name}->{tag} = $name;          $out->{$name}->{$type} = \@o;
         $out->{$name}->{display} = \@o;  
501  }  }
502    
503    sub display { _field( 'display', @_ ) }
504    
505  =head2 search  =head2 search
506    
507  Prepare values just for I<search>  Prepare values just for I<search>
# Line 434  Prepare values just for I<search> Line 510  Prepare values just for I<search>
510    
511  =cut  =cut
512    
513  sub search {  sub search { _field( 'search', @_ ) }
514          my $name = shift or die "search needs name as first argument";  
515          my @o = grep { defined($_) && $_ ne '' } @_;  =head2 sorted
516          return unless (@o);  
517          $out->{$name}->{tag} = $name;  Insert into lists which will be automatically sorted
518          $out->{$name}->{search} = \@o;  
519  }   sorted('Title', rec('200','a') );
520    
521    =cut
522    
523    sub sorted { _field( 'sorted', @_ ) }
524    
525    
526  =head2 marc_leader  =head2 marc_leader
527    
# Line 455  sub marc_leader { Line 536  sub marc_leader {
536          my ($offset,$value) = @_;          my ($offset,$value) = @_;
537    
538          if ($offset) {          if ($offset) {
539                  $out->{' leader'}->{ $offset } = $value;                  $marc_leader->[ $marc_record_offset ]->{ $offset } = $value;
540          } else {          } else {
541                  return $out->{' leader'};                  
542                    if (defined($marc_leader)) {
543                            die "marc_leader not array = ", dump( $marc_leader ) unless (ref($marc_leader) eq 'ARRAY');
544                            return $marc_leader->[ $marc_record_offset ];
545                    } else {
546                            return;
547                    }
548            }
549    }
550    
551    =head2 marc_fixed
552    
553    Create control/indentifier fields with values in fixed positions
554    
555      marc_fixed('008', 00, '070402');
556      marc_fixed('008', 39, '|');
557    
558    Positions not specified will be filled with spaces (C<0x20>).
559    
560    There will be no effort to extend last specified value to full length of
561    field in standard.
562    
563    =cut
564    
565    sub marc_fixed {
566            my ($f, $pos, $val) = @_;
567            die "need marc(field, position, value)" unless defined($f) && defined($pos);
568    
569            confess "need val" unless defined $val;
570    
571            my $update = 0;
572    
573            map {
574                    if ($_->[0] eq $f) {
575                            my $old = $_->[1];
576                            if (length($old) <= $pos) {
577                                    $_->[1] .= ' ' x ( $pos - length($old) ) . $val;
578                                    warn "## marc_fixed($f,$pos,'$val') append '$old' -> '$_->[1]'\n" if ($debug > 1);
579                            } else {
580                                    $_->[1] = substr($old, 0, $pos) . $val . substr($old, $pos + length($val));
581                                    warn "## marc_fixed($f,$pos,'$val') update '$old' -> '$_->[1]'\n" if ($debug > 1);
582                            }
583                            $update++;
584                    }
585            } @{ $marc_record->[ $marc_record_offset ] };
586    
587            if (! $update) {
588                    my $v = ' ' x $pos . $val;
589                    push @{ $marc_record->[ $marc_record_offset ] }, [ $f, $v ];
590                    warn "## marc_fixed($f,$pos,'val') created '$v'\n" if ($debug > 1);
591          }          }
592  }  }
593    
# Line 589  sub marc_duplicate { Line 719  sub marc_duplicate {
719           my $m = $marc_record->[ -1 ];           my $m = $marc_record->[ -1 ];
720           die "can't duplicate record which isn't defined" unless ($m);           die "can't duplicate record which isn't defined" unless ($m);
721           push @{ $marc_record }, dclone( $m );           push @{ $marc_record }, dclone( $m );
722           warn "## marc_duplicate = ", dump(@$marc_record), $/ if ($debug > 1);           push @{ $marc_leader }, dclone( marc_leader() );
723             warn "## marc_duplicate = ", dump(@$marc_leader, @$marc_record), $/ if ($debug > 1);
724           $marc_record_offset = $#{ $marc_record };           $marc_record_offset = $#{ $marc_record };
725           warn "## marc_record_offset = $marc_record_offset", $/ if ($debug > 1);           warn "## marc_record_offset = $marc_record_offset", $/ if ($debug > 1);
726    
727  }  }
728    
729  =head2 marc_remove  =head2 marc_remove
# Line 603  Remove some field or subfield from MARC Line 735  Remove some field or subfield from MARC
735    
736  This will erase field C<200> or C<200^a> from current MARC record.  This will erase field C<200> or C<200^a> from current MARC record.
737    
738      marc_remove('*');
739    
740    Will remove all fields in current MARC record.
741    
742  This is useful after calling C<marc_duplicate> or on it's own (but, you  This is useful after calling C<marc_duplicate> or on it's own (but, you
743  should probably just remove that subfield definition if you are not  should probably just remove that subfield definition if you are not
744  using C<marc_duplicate>).  using C<marc_duplicate>).
# Line 620  sub marc_remove { Line 756  sub marc_remove {
756    
757          warn "### marc_remove before = ", dump( $marc ), $/ if ($debug > 2);          warn "### marc_remove before = ", dump( $marc ), $/ if ($debug > 2);
758    
759          my $i = 0;          if ($f eq '*') {
760          foreach ( 0 .. $#{ $marc } ) {  
761                  last unless (defined $marc->[$i]);                  delete( $marc_record->[ $marc_record_offset ] );
762                  warn "#### working on ",dump( @{ $marc->[$i] }), $/ if ($debug > 3);                  warn "## full marc_record = ", dump( @{ $marc_record }), $/ if ($debug > 1);
763                  if ($marc->[$i]->[0] eq $f) {  
764                          if (! defined $sf) {          } else {
765                                  # remove whole field  
766                                  splice @$marc, $i, 1;                  my $i = 0;
767                                  warn "#### slice \@\$marc, $i, 1 = ",dump( @{ $marc }), $/ if ($debug > 3);                  foreach ( 0 .. $#{ $marc } ) {
768                                  $i--;                          last unless (defined $marc->[$i]);
769                          } else {                          warn "#### working on ",dump( @{ $marc->[$i] }), $/ if ($debug > 3);
770                                  foreach my $j ( 0 .. (( $#{ $marc->[$i] } - 3 ) / 2) ) {                          if ($marc->[$i]->[0] eq $f) {
771                                          my $o = ($j * 2) + 3;                                  if (! defined $sf) {
772                                          if ($marc->[$i]->[$o] eq $sf) {                                          # remove whole field
773                                                  # remove subfield                                          splice @$marc, $i, 1;
774                                                  splice @{$marc->[$i]}, $o, 2;                                          warn "#### slice \@\$marc, $i, 1 = ",dump( @{ $marc }), $/ if ($debug > 3);
775                                                  warn "#### slice \@{\$marc->[$i]}, $o, 2 = ", dump( @{ $marc }), $/ if ($debug > 3);                                          $i--;
776                                                  # is record now empty?                                  } else {
777                                                  if ($#{ $marc->[$i] } == 2) {                                          foreach my $j ( 0 .. (( $#{ $marc->[$i] } - 3 ) / 2) ) {
778                                                          splice @$marc, $i, 1;                                                  my $o = ($j * 2) + 3;
779                                                          warn "#### slice \@\$marc, $i, 1 = ", dump( @{ $marc }), $/ if ($debug > 3);                                                  if ($marc->[$i]->[$o] eq $sf) {
780                                                          $i--;                                                          # remove subfield
781                                                  };                                                          splice @{$marc->[$i]}, $o, 2;
782                                                            warn "#### slice \@{\$marc->[$i]}, $o, 2 = ", dump( @{ $marc }), $/ if ($debug > 3);
783                                                            # is record now empty?
784                                                            if ($#{ $marc->[$i] } == 2) {
785                                                                    splice @$marc, $i, 1;
786                                                                    warn "#### slice \@\$marc, $i, 1 = ", dump( @{ $marc }), $/ if ($debug > 3);
787                                                                    $i--;
788                                                            };
789                                                    }
790                                          }                                          }
791                                  }                                  }
792                          }                          }
793                            $i++;
794                  }                  }
                 $i++;  
         }  
795    
796          warn "### marc_remove($f", $sf ? ",$sf" : "", ") after = ", dump( $marc ), $/ if ($debug > 2);                  warn "### marc_remove($f", $sf ? ",$sf" : "", ") after = ", dump( $marc ), $/ if ($debug > 2);
797    
798          $marc_record->[ $marc_record_offset ] = $marc;                  $marc_record->[ $marc_record_offset ] = $marc;
799            }
800    
801          warn "## full marc_record = ", dump( @{ $marc_record }), $/ if ($debug > 1);          warn "## full marc_record = ", dump( @{ $marc_record }), $/ if ($debug > 1);
802  }  }
# Line 727  sub marc_original_order { Line 871  sub marc_original_order {
871          warn "## marc_record = ", dump( $marc_record ),$/ if ($debug > 1);          warn "## marc_record = ", dump( $marc_record ),$/ if ($debug > 1);
872  }  }
873    
874    =head2 marc_count
875    
876    Return number of MARC records created using L</marc_duplicate>.
877    
878      print "created ", marc_count(), " records";
879    
880    =cut
881    
882    sub marc_count {
883            return $#{ $marc_record };
884    }
885    
886    
887  =head1 Functions to extract data from input  =head1 Functions to extract data from input
888    
# Line 749  sub _pack_subfields_hash { Line 905  sub _pack_subfields_hash {
905    
906          my ($h,$include_subfields) = @_;          my ($h,$include_subfields) = @_;
907    
908            # sanity and ease of use
909            return $h if (ref($h) ne 'HASH');
910    
911          if ( defined($h->{subfields}) ) {          if ( defined($h->{subfields}) ) {
912                  my $sfs = delete $h->{subfields} || die "no subfields?";                  my $sfs = delete $h->{subfields} || die "no subfields?";
913                  my @out;                  my @out;
# Line 848  syntaxtic sugar for Line 1007  syntaxtic sugar for
1007    @v = rec('200')    @v = rec('200')
1008    @v = rec('200','a')    @v = rec('200','a')
1009    
1010    If rec() returns just single value, it will
1011    return scalar, not array.
1012    
1013  =cut  =cut
1014    
1015    sub frec {
1016            my @out = rec(@_);
1017            warn "rec(",dump(@_),") has more than one return value, ignoring\n" if $#out > 0;
1018            return shift @out;
1019    }
1020    
1021  sub rec {  sub rec {
1022          my @out;          my @out;
1023          if ($#_ == 0) {          if ($#_ == 0) {
# Line 857  sub rec { Line 1025  sub rec {
1025          } elsif ($#_ == 1) {          } elsif ($#_ == 1) {
1026                  @out = rec2(@_);                  @out = rec2(@_);
1027          }          }
1028          if (@out) {          if ($#out == 0 && ! wantarray) {
1029                    return $out[0];
1030            } elsif (@out) {
1031                  return @out;                  return @out;
1032          } else {          } else {
1033                  return '';                  return '';
# Line 893  Prefix all values with a string Line 1063  Prefix all values with a string
1063  =cut  =cut
1064    
1065  sub prefix {  sub prefix {
1066          my $p = shift or return;          my $p = shift;
1067            return @_ unless defined( $p );
1068          return map { $p . $_ } grep { defined($_) } @_;          return map { $p . $_ } grep { defined($_) } @_;
1069  }  }
1070    
# Line 906  suffix all values with a string Line 1077  suffix all values with a string
1077  =cut  =cut
1078    
1079  sub suffix {  sub suffix {
1080          my $s = shift or die "suffix needs string as first argument";          my $s = shift;
1081            return @_ unless defined( $s );
1082          return map { $_ . $s } grep { defined($_) } @_;          return map { $_ . $s } grep { defined($_) } @_;
1083  }  }
1084    
# Line 919  surround all values with a two strings Line 1091  surround all values with a two strings
1091  =cut  =cut
1092    
1093  sub surround {  sub surround {
1094          my $p = shift or die "surround need prefix as first argument";          my $p = shift;
1095          my $s = shift or die "surround needs suffix as second argument";          my $s = shift;
1096            $p = '' unless defined( $p );
1097            $s = '' unless defined( $s );
1098          return map { $p . $_ . $s } grep { defined($_) } @_;          return map { $p . $_ . $s } grep { defined($_) } @_;
1099  }  }
1100    
# Line 941  sub first { Line 1115  sub first {
1115    
1116  Consult lookup hashes for some value  Consult lookup hashes for some value
1117    
1118    @v = lookup( $v );    @v = lookup(
1119    @v = lookup( @v );          sub {
1120                    'ffkk/peri/mfn'.rec('000')
1121            },
1122            'ffkk','peri','200-a-200-e',
1123            sub {
1124                    first(rec(200,'a')).' '.first(rec('200','e'))
1125            }
1126      );
1127    
1128    Code like above will be B<automatically generated> using L<WebPAC::Parse> from
1129    normal lookup definition in C<conf/lookup/something.pl> which looks like:
1130    
1131  FIXME B<currently this one is broken!>    lookup(
1132            # which results to return from record recorded in lookup
1133            sub { 'ffkk/peri/mfn' . rec('000') },
1134            # from which database and input
1135            'ffkk','peri',
1136            # such that following values match
1137            sub { first(rec(200,'a')) . ' ' . first(rec('200','e')) },
1138            # if this part is missing, we will try to match same fields
1139            # from lookup record and current one, or you can override
1140            # which records to use from current record using
1141            sub { rec('900','x') . ' ' . rec('900','y') },
1142      )
1143    
1144    You can think about this lookup as SQL (if that helps):
1145    
1146      select
1147            sub { what }
1148      from
1149            database, input
1150      where
1151        sub { filter from lookuped record }
1152      having
1153        sub { optional filter on current record }
1154    
1155    Easy as pie, right?
1156    
1157  =cut  =cut
1158    
1159  sub lookup {  sub lookup {
1160          my $k = shift or return;          my ($what, $database, $input, $key, $having) = @_;
1161          return unless (defined($lookup->{$k}));  
1162          if (ref($lookup->{$k}) eq 'ARRAY') {          confess "lookup needs 5 arguments: what, database, input, key, having\n" unless ($#_ == 4);
1163                  return @{ $lookup->{$k} };  
1164            warn "## lookup ($database, $input, $key)", $/ if ($debug > 1);
1165            return unless (defined($lookup->{$database}->{$input}->{$key}));
1166    
1167            confess "lookup really need load_row_coderef added to data_structure\n" unless ($load_row_coderef);
1168    
1169            my $mfns;
1170            my @having = $having->();
1171    
1172            warn "## having = ", dump( @having ) if ($debug > 2);
1173    
1174            foreach my $h ( @having ) {
1175                    if (defined($lookup->{$database}->{$input}->{$key}->{$h})) {
1176                            warn "lookup for $database/$input/$key/$h return ",dump($lookup->{$database}->{$input}->{$key}->{$h}),"\n" if ($debug);
1177                            $mfns->{$_}++ foreach keys %{ $lookup->{$database}->{$input}->{$key}->{$h} };
1178                    }
1179            }
1180    
1181            return unless ($mfns);
1182    
1183            my @mfns = sort keys %$mfns;
1184    
1185            warn "# lookup loading $database/$input/$key mfn ", join(",",@mfns)," having ",dump(@having),"\n" if ($debug);
1186    
1187            my $old_rec = $rec;
1188            my @out;
1189    
1190            foreach my $mfn (@mfns) {
1191                    $rec = $load_row_coderef->( $database, $input, $mfn );
1192    
1193                    warn "got $database/$input/$mfn = ", dump($rec), $/ if ($debug);
1194    
1195                    my @vals = $what->();
1196    
1197                    push @out, ( @vals );
1198    
1199                    warn "lookup for mfn $mfn returned ", dump(@vals), $/ if ($debug);
1200            }
1201    
1202    #       if (ref($lookup->{$k}) eq 'ARRAY') {
1203    #               return @{ $lookup->{$k} };
1204    #       } else {
1205    #               return $lookup->{$k};
1206    #       }
1207    
1208            $rec = $old_rec;
1209    
1210            warn "## lookup returns = ", dump(@out), $/ if ($debug);
1211    
1212            if ($#out == 0) {
1213                    return $out[0];
1214          } else {          } else {
1215                  return $lookup->{$k};                  return @out;
1216          }          }
1217  }  }
1218    
1219  =head2 save_into_lookup  =head2 save_into_lookup
1220    
1221  Save value into lookup.  Save value into lookup. It associates current database, input
1222    and specific keys with one or more values which will be
1223    associated over MFN.
1224    
1225    MFN will be extracted from first occurence current of field 000
1226    in current record, or if it doesn't exist from L<_set_config> C<_mfn>.
1227    
1228    save_into_lookup($database,$input,$key,sub {    my $nr = save_into_lookup($database,$input,$key,sub {
1229          # code which produce one or more values          # code which produce one or more values
1230    });    });
1231    
1232  This function shouldn't be called directly, it's called from code created by L<WebPAC::Parser>.  It returns number of items saved.
1233    
1234    This function shouldn't be called directly, it's called from code created by
1235    L<WebPAC::Parser>.
1236    
1237  =cut  =cut
1238    
# Line 976  sub save_into_lookup { Line 1242  sub save_into_lookup {
1242          die "save_into_lookup needs input" unless defined($input);          die "save_into_lookup needs input" unless defined($input);
1243          die "save_into_lookup needs key" unless defined($key);          die "save_into_lookup needs key" unless defined($key);
1244          die "save_into_lookup needs CODE" unless ( defined($coderef) && ref($coderef) eq 'CODE' );          die "save_into_lookup needs CODE" unless ( defined($coderef) && ref($coderef) eq 'CODE' );
1245          my $mfn = $rec->{'000'}->[0] || die "mfn not defined or zero";  
1246            warn "## save_into_lookup rec = ", dump($rec), " config = ", dump($config), $/ if ($debug > 2);
1247    
1248            my $mfn =
1249                    defined($rec->{'000'}->[0])     ?       $rec->{'000'}->[0]      :
1250                    defined($config->{_mfn})        ?       $config->{_mfn}         :
1251                                                                                    die "mfn not defined or zero";
1252    
1253            my $nr = 0;
1254    
1255          foreach my $v ( $coderef->() ) {          foreach my $v ( $coderef->() ) {
1256                  $lookup->{$database}->{$input}->{$key}->{$v}->{$mfn}++;                  $lookup->{$database}->{$input}->{$key}->{$v}->{$mfn}++;
1257                  warn "# saved lookup $database/$input/$key [$v] $mfn\n" if ($debug > 1);                  warn "# saved lookup $database/$input/$key [$v] $mfn\n" if ($debug > 1);
1258                    $nr++;
1259          }          }
1260    
1261            return $nr;
1262  }  }
1263    
1264  =head2 config  =head2 config
# Line 991  Consult config values stored in C<config Line 1269  Consult config values stored in C<config
1269    $database_code = config();    # use _ from hash    $database_code = config();    # use _ from hash
1270    $database_name = config('name');    $database_name = config('name');
1271    $database_input_name = config('input name');    $database_input_name = config('input name');
   $tag = config('input normalize tag');  
1272    
1273  Up to three levels are supported.  Up to three levels are supported.
1274    
# Line 1107  sub split_rec_on { Line 1384  sub split_rec_on {
1384          }          }
1385  }  }
1386    
1387    my $hash;
1388    
1389    =head2 set
1390    
1391      set( key => 'value' );
1392    
1393    =cut
1394    
1395    sub set {
1396            my ($k,$v) = @_;
1397            warn "## set ( $k => ", dump($v), " )", $/ if ( $debug );
1398            $hash->{$k} = $v;
1399    };
1400    
1401    =head2 get
1402    
1403      get( 'key' );
1404    
1405    =cut
1406    
1407    sub get {
1408            my $k = shift || return;
1409            my $v = $hash->{$k};
1410            warn "## get $k = ", dump( $v ), $/ if ( $debug );
1411            return $v;
1412    }
1413    
1414    =head2 count
1415    
1416      if ( count( @result ) == 1 ) {
1417            # do something if only 1 result is there
1418      }
1419    
1420    =cut
1421    
1422    sub count {
1423            warn "## count ",dump(@_),$/ if ( $debug );
1424            return @_ . '';
1425    }
1426    
1427  # END  # END
1428  1;  1;

Legend:
Removed from v.721  
changed lines
  Added in v.983

  ViewVC Help
Powered by ViewVC 1.1.26