code_junkie

How can I execute a given function on every element of a complicated data structure in Perl?

Nov 13th, 2011
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. sub _html_decode {
  2. my $self = shift;
  3. my $ref = shift;
  4.  
  5. if (ref($ref) eq "HASH") {
  6. $self->_html_decode_hash($ref)
  7. }
  8. if (ref($ref) eq "ARRAY") {
  9. $self->_html_decode_array($ref);
  10. }
  11.  
  12. }
  13.  
  14. sub _html_decode_array {
  15. my $self = shift;
  16. my $ref = shift;
  17.  
  18. unless (@$ref) {return;}
  19.  
  20. foreach (0 .. (scalar(@$ref) - 1)) {
  21. if (ref($ref->[$_]) eq "HASH") {
  22. $self->_html_decode_hash($ref->[$_]);
  23. }
  24. if (ref($ref->[$_]) eq "ARRAY") {
  25. $self->_html_decode_array($ref->[$_]);
  26. }
  27. else {
  28. $ref->[$_] = decode_entities($ref->[$_]);
  29. }
  30. }
  31. }
  32.  
  33. sub _html_decode_hash {
  34. my $self = shift;
  35. my $ref = shift;
  36.  
  37. unless (%$ref) {return;}
  38.  
  39. while (my ($k, $v) = each %$ref) {
  40. if (ref($v) eq "HASH") {
  41. $self->_html_decode_hash($v);
  42. }
  43. if (ref($v) eq "ARRAY") {
  44. $self->_html_decode_array($v)
  45. }
  46. else {
  47. $ref->{$k} = decode_entities($v);
  48. }
  49. }
  50. }
  51.  
  52. sub _html_decode {
  53. my ($self, $ref) = @_;
  54.  
  55. if (ref($ref) eq "HASH") {
  56. for my $value (values %{$ref}) {
  57. $self->_html_decode($value);
  58. }
  59. }
  60. elsif (ref($ref) eq "ARRAY") {
  61. for my $value (@{$ref}) {
  62. $self->_html_decode($value);
  63. }
  64. }
  65. else {
  66. $_[1] = decode_entities($_[1]);
  67. }
  68. }
Add Comment
Please, Sign In to add comment