SHARE
TWEET

Test of parse_replacement version 3

hakonhagland Mar 15th, 2015 238 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use feature qw(say);
  2. use strict;
  3. use warnings;
  4.  
  5. use Carp;
  6. use Data::Dump qw(dd dump);
  7. use Scalar::Util 'reftype';
  8.  
  9. # Test cases:
  10. # Format:
  11. #   string,       regex,    replacement, expected
  12. my @test_cases = (
  13.     ['aba',      'a(.*?)a', '$1',      'b'],
  14.     ['yyababaxxa', 'a(.*?)a', '$1',    'yybbxx'],
  15.     ['acccb',    'a(.*?)b', '$1\$',    'ccc$'],
  16.     ['abxybaxy', '(x)(y)',  '${2}3$1', 'aby3xbay3x']
  17. );
  18.  
  19. for (0..$#test_cases) {
  20.     say "Case " . ($_ + 1);
  21.     say "--------";
  22.     my ($str, $regex, $replacement, $expected_result) = @{$test_cases[$_]};
  23.     say "String: '$str'";
  24.     say "Regex: " . dump($regex);
  25.     say "Replacement: '$replacement'";
  26.     say "Expected: '$expected_result'";
  27.     my $result_str = $str;
  28.     pos( $str ) = 0;
  29.     pos( $result_str ) = 0;
  30.     while (1) {
  31.         my @captures = $str =~ /\G.*?$regex/;
  32.         last if @captures == 0;
  33.         pos($str) = $+[0];
  34.         my $func = parse_replacement( $replacement );
  35.         my $result = $func->(\@captures);
  36.         if ($result_str =~ s/\G.*?\K$regex/$result/) {
  37.             my $length_of_match = ($+[0] - $-[0]);
  38.             my $offset = length( $result ) - $length_of_match;
  39.             pos( $result_str ) = $+[0] + $offset;
  40.         } else {
  41.             croak "No replacements is unexpected at this point!";
  42.         }
  43.     }
  44.     say "Result2: '$result_str'";
  45.     say "Test result: " . (($expected_result eq $result_str) ? "passed" : "failed");
  46.     say "";
  47. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top