++ed by:

1 non-PAUSE user.

Author image Stephen D. Wells


Data::SearchReplace - perl extention for searching and replacing entries in complex data structures


  use Data::SearchReplace ('sr');
  sr({ SEARCH => 'searching', REPLACE => 'replacing'}, \$complex_var);

  # or OO

  use Data::SearchReplace;
  $sr = Data::SearchReplace->new({ SEARCH => 'search for this',
                                   REPLACE => 'replace with this' });


  # if you want more control over your search/replace pattern you
  #  can pass an entire regex instead complete with attributes

  sr({ REGEX => 's/nice/great/gi' }, \$complex_var);

  # you can even use a subroutine if you'd like
  #  the input variable is the value and the return sets the new
  #  value.

  sr({ CODE => sub { uc($_[0]) } }, \$complex_var);

  # now sr has a return value for the number of variables it changed
  my $ret = sr({ SEARCH => 'searching', REPLACE => 'replacing'}, \$complex_var);

  # returns the number of variables it matched


Data::SearchReplace - run a regex on all values within a complex data structure.

 use Data::SearchReplace qw(sr);
 sr({SEARCH => 'find', REPLACE => 'replace'}, \@data);
 sr({REGEX  => 's/find/replace/g'}, \%data);
 sr({CODE   => sub {uc($_[0])} }, \@data);
 my $matched = sr({REGEX  => 's/find/replace/g'}, \%data);


Data::SearchReplace is used when you want to run a regex on all the entries of a complex data structure.


 use Data::SearchReplace qw(sr);
 %VAR = ( example => { drink => [ qw(wine beer kool-aid) ],
                       food  => 'and lots of it',
                       dessert => { strawberry => 'shortcake and cream',
                                    liver      => 'not on my diet',
                                    ice_cream  => 'works for me'} },
          filler  => 'naturally you can put whatever you want here',
          test    => 'this should change too' );
 # we'll capitalize the first character and strip off any extra words
 my $matched = sr({ REGEX => 's/(\w+).*/ucfirst($1)/e' }, \%VAR);

 print "Hey my program ", $VAR{example}->{dessert}->{ice_cream}, "!\n",
       $VAR{test}, " should work for you too!\n",
       "btw it altered $matched variables in this example.\n";


sr - however none by default


This doesn't work well for CODE (subroutines) or GLOB (typeglobs). I'm not entirely certain how one would even go about working on these.

Also you should never pass a reference to a reference to the routine. In other words something like this will NOT work:

 my $complex_var = { hello => [qw(world earth)] };

  sr({ SEARCH => 'world', REPLACE => 'planet' }, \$complex_var);

  just use...

  sr({ SEARCH => 'world', REPLACE => 'planet' }, $complex_var);


Stephen D. Wells, <wells@cedarnet.org>


Copyright 2003-2007 (C) by Stephen D. Wells. All rights reserved.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.