/[cvs]/nfo/perl/libs/Data/Mungle/Transform/Deep.pm
ViewVC logotype

Diff of /nfo/perl/libs/Data/Mungle/Transform/Deep.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.6 by jonen, Mon Dec 23 11:27:53 2002 UTC revision 1.13 by joko, Fri Feb 21 01:48:50 2003 UTC
# Line 1  Line 1 
1  ##############################################  ## ---------------------------------------------------------------------------
2  #  ##  $Id$
3  #  $Id$  ## ---------------------------------------------------------------------------
4  #  ##  $Log$
5  #  $Log$  ##  Revision 1.13  2003/02/21 01:48:50  joko
6  #  Revision 1.6  2002/12/23 11:27:53  jonen  ##  renamed core function
7  #  + changed behavior WATCH!  ##
8  #  ##  Revision 1.12  2003/02/20 22:45:19  joko
9  #  Revision 1.5  2002/12/16 19:57:54  joko  ##  fix regarding new deep_copy
10  #  + option 'init'  ##
11  #  ##  Revision 1.11  2003/02/20 21:13:54  joko
12  #  Revision 1.4  2002/12/05 13:56:49  joko  ##  - removed implementation of deep_copy2 - get this from the Pitonyak namespace (now cloned to repository)
13  #  - var_deref  ##
14  #  + expand - more sophisticated dereferencing with callbacks using Iterate  ##  Revision 1.10  2003/02/20 20:48:00  joko
15  #  ##  - refactored lots of code to Data::Code::Ref
16  #  Revision 1.3  2002/12/03 05:34:55  joko  ##  + alternative 'deep_copy' implementation
17  #  + bugfix: now utilizing var_utf2iso from Data::Transform::Encode  ##
18  #  ##  Revision 1.9  2003/02/18 19:35:56  joko
19  #  Revision 1.2  2002/12/01 04:44:07  joko  ##  +- modified 'sub refexpr2perlref': now can get the $delimiter passed, too
20  #  + code from Data::Transform::OO  ##
21  #  ##  Revision 1.8  2003/02/09 05:10:56  joko
22  #  Revision 1.1  2002/11/29 04:49:20  joko  ##  + minor update
23  #  + initial check-in  ##
24  #  ##  Revision 1.7  2003/01/19 03:26:59  joko
25  #  Revision 1.1  2002/10/10 03:26:00  cvsjoko  ##  + added 'sub deep_copy'  -  refactored from libp
26  #  + new  ##  + add 'sub merge'  -  exported from CPAN's 'Hash::Merge'
27  #  ##
28  ##############################################  ##  Revision 1.6  2002/12/23 11:27:53  jonen
29    ##  + changed behavior WATCH!
30    ##
31    ##  Revision 1.5  2002/12/16 19:57:54  joko
32    ##  + option 'init'
33    ##
34    ##  Revision 1.4  2002/12/05 13:56:49  joko
35    ##  - var_deref
36    ##  + expand - more sophisticated dereferencing with callbacks using Iterate
37    ##
38    ##  Revision 1.3  2002/12/03 05:34:55  joko
39    ##  + bugfix: now utilizing var_utf2iso from Data::Transform::Encode
40    ##
41    ##  Revision 1.2  2002/12/01 04:44:07  joko
42    ##  + code from Data::Transform::OO
43    ##
44    ##  Revision 1.1  2002/11/29 04:49:20  joko
45    ##  + initial check-in
46    ##
47    ##  Revision 1.1  2002/10/10 03:26:00  cvsjoko
48    ##  + new
49    ## ---------------------------------------------------------------------------
50    
51    
52  package Data::Transform::Deep;  package Data::Transform::Deep;
# Line 36  use warnings; Line 57  use warnings;
57  require Exporter;  require Exporter;
58  our @ISA = qw( Exporter );  our @ISA = qw( Exporter );
59  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
   &var_NumericalHashToArray  
   &var_mixin  
   &object2hash  
   &hash2object  
   &refexpr2perlref  
60    &expand    &expand
61      &deep_copy
62      &merge_to
63  );  );
64  #  &var_deref  
 #  &getStructSlotByStringyAddress  
65    
66  use attributes;  use attributes;
67  use Data::Dumper;  use Data::Dumper;
 use Data::Transform::Encode qw( var_utf2iso var2utf8 scalar2utf8 );  
 use libp qw( deep_copy );  
68  use Iterate;  use Iterate;
69    
70  sub var_NumericalHashToArray {  use Pitonyak::DeepCopy;
71    use Data::Transform::Encode qw( latin_to_utf8 latin_to_utf8_scalar utf8_to_latin utf8_to_latin_scalar );
72    use Data::Code::Ref qw( ref_slot );
73    
74    sub numhash2list {
75    my $vref = shift;    my $vref = shift;
76    #my $context = shift;    #my $context = shift;
77    if (ref $vref eq 'HASH') {    if (ref $vref eq 'HASH') {
# Line 68  sub var_NumericalHashToArray { Line 87  sub var_NumericalHashToArray {
87                }                }
88                $vref->{$_} = \@arr;                $vref->{$_} = \@arr;
89              }              }
90              var_NumericalHashToArray($vref->{$_});              numhash2list($vref->{$_});
91            }            }
92  #      } else {  #      } else {
93  #        #$vref->{$_} = scalar2iso($vref->{$_});  #        #$vref->{$_} = scalar2iso($vref->{$_});
# Line 78  sub var_NumericalHashToArray { Line 97  sub var_NumericalHashToArray {
97  }  }
98    
99    
100  sub var_deref {  # FIXME: could this be refactored using expand?
101    # btw: "expand": look at scripts@CPAN (System Administration):
102    # there is a perl make with perl
103    sub _var_deref_test {
104    my $obj = shift;    my $obj = shift;
105    my $options = shift;    my $options = shift;
106    my $result;    my $result;
# Line 117  sub var_deref { Line 139  sub var_deref {
139  }  }
140    
141    
142    # convert values in hash to utf8 (and back) to be ready for (e.g.) encapsulation in XML
143    # but still using the known latin locale stuff
144  sub expand {  sub expand {
145    
146    my $obj = shift;    my $obj = shift;
147    my $options = shift;    my $options = shift;
148    my $result;    my $result;
149    
150    if ((ref $obj) eq 'ARRAY') {    #print "ref: ", ref $obj, "\n";
151    
152      if (ref $obj eq 'ARRAY') {
153    
154      IterArray @$obj, sub {      IterArray @$obj, sub {
155        my $item;        my $item;
# Line 139  sub expand { Line 165  sub expand {
165          #$item = deep_copy($_[0]);          #$item = deep_copy($_[0]);
166          $item = $_[0];          $item = $_[0];
167          # conversions/encodings          # conversions/encodings
168          $item = scalar2utf8($item) if ($item && $options->{utf8});          $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
169            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
170        }        }
171        #push(@{$result}, $item) if $item;   # use item only if not undef  (TODO: make configurable via $options)        #push(@{$result}, $item) if $item;   # use item only if not undef  (TODO: make configurable via $options)
172        push(@{$result}, $item);                 # use item in any case        push(@{$result}, $item);                 # use item in any case
173    
174      }      }
175    
176      } elsif (ref $obj eq 'CODE') {
177        #print Dumper($obj);
178        #exit;
179    
180    # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???    # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
181    } else {    } elsif (ref $obj) {
182    
183      IterHash %$obj, sub {      IterHash %$obj, sub {
184        my $item;        my $item;
# Line 164  sub expand { Line 195  sub expand {
195          #$item = deep_copy($_[1]);          #$item = deep_copy($_[1]);
196          $item = $_[1];          $item = $_[1];
197          # conversions/encodings          # conversions/encodings
198          $item = scalar2utf8($item) if ($item && $options->{utf8});          $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
199            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
200        }        }
201        #$result->{$_[0]} = $item if $item;   # use item only if not undef  (TODO: make configurable via $options)        #$result->{$_[0]} = $item if $item;   # use item only if not undef  (TODO: make configurable via $options)
202        $result->{$_[0]} = $item;               # use item in any case        $result->{$_[0]} = $item;               # use item in any case
203      }      }
204    
205      } else {
206        #die ("not a reference!");
207        $result = $obj;
208    
209    }    }
210    
211    # convert all values to utf8 (inside complex struct)    # convert all values to utf8 (inside complex struct)
212      # now done in core-item-callbacks via Greg London's "Iterate" from CPAN      # now done in core-item-callbacks via Greg London's "Iterate" from CPAN
213      # var2utf8($result) if ($options->{utf8});      # latin_to_utf8($result) if ($options->{utf8});
214    
215    # destroy persistent object from memory to be sure to get a fresh one next time    # destroy persistent object from memory to be sure to get a fresh one next time
216    #undef $obj if $options->{destroy};    #undef $obj if $options->{destroy};
# Line 187  sub expand { Line 223  sub expand {
223    
224    
225  my @indexstack;  my @indexstack;
226  sub var_traverse_mixin_update {  sub _var_traverse_mixin_update_old {
227    my $obj = shift;    my $obj = shift;
228    my $data = shift;    my $data = shift;
229    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 231  sub var_traverse_mixin_update { Line 267  sub var_traverse_mixin_update {
267    #return $result;    #return $result;
268  }  }
269    
270  sub object2hash {  sub merge_to {
271    my $object = shift;    _hash2object(@_);
272    my $options = shift;    # TODO:
273    #my $deref = var_deref($object);    # re-implement using CPAN's "Iterate".
   my $deref = expand($object, $options);  
   #var2utf8($deref) if ($options->{utf8});  
   return $deref;  
274  }  }
275    
276    
277  # todo: maybe do diff(s) here sometimes!?  # todo: maybe do diff(s) here sometimes!?
278  sub hash2object {  sub _hash2object {
279    my $object = shift;    my $object = shift;
280    my $data = shift;    my $data = shift;
281    my $options = shift;    my $options = shift;
# Line 250  sub hash2object { Line 284  sub hash2object {
284        
285    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,
286    # this method corrects this    # this method corrects this
287    var_NumericalHashToArray($data) if ($options->{php});    numhash2list($data) if ($options->{php});
288    
289    # utf8-conversion/-encoding (essential for I18N)    # utf8-conversion/-encoding (essential for I18N)
290    var_utf2iso($data) if ($options->{utf8});    var_utf2iso($data) if ($options->{utf8});
# Line 262  sub hash2object { Line 296  sub hash2object {
296    #my $obj = $self->getObject($oid);    #my $obj = $self->getObject($oid);
297    
298    # mix changes into fresh object and save it back    # mix changes into fresh object and save it back
299    hash2object_traverse_mixin($object, $data, 0, $options);    _hash2object_traverse_mixin($object, $data, 0, $options);
300    
301    # done in core mixin function?    # done in core mixin function?
302    #$self->{storage}->update($obj);    #$self->{storage}->update($obj);
# Line 285  sub hash2object { Line 319  sub hash2object {
319  #my @indexstack;  #my @indexstack;
320    
321  # traverse a deeply nested structure, mix in values from given hash, update underlying tangram-object  # traverse a deeply nested structure, mix in values from given hash, update underlying tangram-object
322  sub hash2object_traverse_mixin {  sub _hash2object_traverse_mixin {
323    my $object = shift;    my $object = shift;
324    my $data = shift;    my $data = shift;
325    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 303  sub hash2object_traverse_mixin { Line 337  sub hash2object_traverse_mixin {
337    # what's exactly done here? hmmm.... it works ;)    # what's exactly done here? hmmm.... it works ;)
338    # maybe a HACK: please try not to use "IntrHash"es, maybe this cannot handle them!!!    # maybe a HACK: please try not to use "IntrHash"es, maybe this cannot handle them!!!
339    # extend! check!    # extend! check!
340    if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {    
341      #print attributes::reftype($object), "\n";
342      
343      # V1
344      #if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {
345      # V2
346      my $reftype = attributes::reftype($object);
347      #print "reftype: '$reftype'", "\n";
348      if ($reftype eq 'HASH') {
349    
350  #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";  #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";
351                    
# Line 316  sub hash2object_traverse_mixin { Line 358  sub hash2object_traverse_mixin {
358  #    @fields = keys %{$data} if $options->{mixin};  #    @fields = keys %{$data} if $options->{mixin};
359            
360      foreach (@fields) {      foreach (@fields) {
361        push @indexstack, $_;        my $field = $_;
362          push @indexstack, $field;
363                            
364        # determine type of object        # determine type of object
365        my $ref = ref $object->{$_};        my $ref = ref $object->{$field};
366  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
367        if ($ref) {        if ($ref) {
368          hash2object_traverse_mixin($object->{$_}, $data, 1, $options);          _hash2object_traverse_mixin($object->{$field}, $data, 1, $options);
369        } else {        } else {
370          my $val = getStructSlotByStringyAddress($data, \@indexstack);          my $val = ref_slot($data, \@indexstack);
371          $object->{$_} = $val if defined $val;          
372    #print Dumper($options);
373            my $field_target = $field;
374            if (my $pattern = $options->{pattern_strip_key}) {
375              print "pattern: $pattern", "\n";
376              $field_target =~ s/$pattern//;
377              print "field: $field_target", "\n";
378            }
379    
380            $object->{$field_target} = $val if defined $val;
381        }        }
382        pop @indexstack;        pop @indexstack;
383      }      }
# Line 358  sub hash2object_traverse_mixin { Line 410  sub hash2object_traverse_mixin {
410  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
411  #      if ($ref && $_) {  #      if ($ref && $_) {
412        if ($ref) {        if ($ref) {
413          hash2object_traverse_mixin($_, $data, 1, $options);          _hash2object_traverse_mixin($_, $data, 1, $options);
414        } else {        } else {
415          $object->[$i] = $_ if defined $_;          $object->[$i] = $_ if defined $_;
416        }        }
417        pop @indexstack;        pop @indexstack;
418        $i++;        $i++;
419      }      }
420    
421    =pod
422      # object?
423      } else {
424        print "reference: ", ref $object, "\n";
425        print "reftype: ", $reftype, "\n";
426        die(__PACKAGE__ . "->_hash2object_traverse_mixin: can not handle this!");
427    =cut
428      
429    }    }
430    
431  }  }
432    
433    
434  # this function seems to do similar stuff like these below (refexpr2perlref & co.)  # ACK's go to Randal L. Schwartz <merlyn@stonehenge.com>
435  # TODO: maybe this mechanism can be replaced completely through some nice module from CPAN .... ?   ;-)  # on the website:
436  sub getStructSlotByStringyAddress {  # This text is copyright by Miller-Freeman, Inc., and is used with their permission.
437    my $var = shift;  # Further distribution or use is not permitted.
438    my $indexstack_ref = shift;  # please visit http://www.stonehenge.com/merlyn/UnixReview/col30.html
439    my @indexstack = @{$indexstack_ref};  sub deep_copy1 {
440    my $joiner = '->';    my $this = shift;
441    my @evlist;    if (not ref $this) {
442    foreach (@indexstack) {      $this;
443      my $elem;    } elsif (ref $this eq "ARRAY") {
444      if ($_ =~ m/\d+/) { $elem = "[$_]"; }      [map deep_copy1($_), @$this];
445      if ($_ =~ m/\D+/) { $elem = "{$_}"; }    } elsif (ref $this eq "HASH") {
446      push @evlist, $elem;      +{map { $_ => deep_copy1($this->{$_}) } keys %$this};
447    }    } elsif (ref $this eq "CODE") {
448    my $evstring = join($joiner, @evlist);      $this;
449    $evstring = 'return $var->' . $evstring . ';';    } else { die "deep_copy1 asks: what type is $this?" }
450    #print "ev: $evstring\n";    #} else { print "deep_copy asks: what type is $this?", "\n"; }
   return eval($evstring);  
451  }  }
452    
453    # ACK's go to Andrew Pitonyak
454  sub refexpr2perlref {  # Copyright 2002, Andrew Pitonyak (perlboy@pitonyak.org)
455    # please visit: http://www.pitonyak.org/code/perl/Pitonyak/DeepCopy.pm.html
456    my $obj = shift;  sub deep_copy {
457    my $expr = shift;    Pitonyak::DeepCopy::deep_copy(@_);
   my $callbackMap = shift;  
   
   my $value;  
   # detect for callback (code-reference)  
   if (ref($expr) eq 'CODE') {  
     $value = &$expr($obj);  
   
   } elsif ($expr =~ m/->/) {  
     # use expr as complex object reference declaration (obj->subObj->subSubObj->0->attribute)  
     (my $objPerlRefString, my $parts) = refexpr2perlref_parts($expr);  
     #print "\n", "expr: $expr";  
     #print "\n", "objPerlRefString: $objPerlRefString";  
     $value = eval('$obj' . '->' . $objPerlRefString);  
       
     # if value isn't set, try to "fallback" to callbackMap  
     # callbacks are applied this way:  
     #   take the last element of the expression parts and check if this string exists as a key in the callback-map  
     if (!$value && $callbackMap) {  
       #print Dumper($callbackMap);  
         
       # prepare needle  
       my @parts = @$parts;  
       my $count = $#parts;  
       my $needle = $parts[$count];  
   
       # prepare haystack  
       my @haystack = keys %$callbackMap;  
       if (grep($needle, @haystack)) {  
         $value = $callbackMap->{$needle}->();  
         #print "value: ", $value, "\n";  
       }  
     }  
   
   } else {  
     # use expr as simple scalar key (attributename)  
     $value = $obj->{$expr};  
   }  
             
   return $value;  
     
458  }  }
459    
460    
 sub refexpr2perlref_parts {  
   my $expr = shift;  
   
   # split expression by dereference operators first  
   my @parts_pure = split(/->/, $expr);  
   
   # wrap []'s around each part, if it consists of numeric characters only (=> numeric = array-index),  
   # use {}'s, if there are word-characters in it (=> alphanumeric = hash-key)  
   my @parts_capsule = @parts_pure;  
   map {  
     m/^\d+$/ && ($_ = "[$_]") || ($_ = "{$_}");  
   } @parts_capsule;  
   
   # join parts with dereference operators together again and return built string  
   return (join('->', @parts_capsule), \@parts_pure);  
 }  
   
461  1;  1;
462    __END__

Legend:
Removed from v.1.6  
changed lines
  Added in v.1.13

MailToCvsAdmin">MailToCvsAdmin
ViewVC Help
Powered by ViewVC 1.1.26 RSS 2.0 feed