http://www.perlmonks.org?node_id=11123474


in reply to Riddle with regex

This does smell a bit homeworky. I also have some questions about details of the requirement specification. However, if I were to approach this problem, I would likely first set up a testing environment with placeholder regexes, then begin refining my understanding of the requirement and the definitions of the regexes. As the requirement clarifies, the regexes will sharpen and the number of test cases will grow.

An initial testing framework (which at least compiles):

use strict; use warnings; use Test::More; use Test::NoWarnings; use Data::Dump qw(pp); my @Tests = ( 'all valid strings', [ qq{"hello"}, 'Valid String' ], [ qq{"hi 'Hello'"}, 'Valid String' ], [ qq{"Hey there\n"}, 'Valid String' ], [ qq{"hi1 \x10"}, 'Valid String' ], [ qq{"hi2 \x3A"}, 'Valid String' ], [ qq{"hi\thow\tare\tyou\tdoing"}, 'Valid String' ], 'various invalid strings', [ qq{'bad"}, 'Close the string!' ], [ qq{"bad}, 'Close the string!' ], [ qq{"multi-line bad\nstring"}, 'Invalid char' ], [ qq{"inner-"-bad"}, 'Invalid char' ], [ qq{"bad escape \\"}, 'Invalid escape' ], ); # end array @Tests my @additional = qw(Test::NoWarnings); # each of these adds 1 test plan 'tests' => (scalar grep { ref eq 'ARRAY' } @Tests) + @additional ; VECTOR: for my $ar_vector (@Tests) { if (not ref $ar_vector) { note $ar_vector; next VECTOR; } my ($string, $expected) = @$ar_vector; my $got = classify($string); is $got, $expected, sprintf "'%s' -> $expected", pp $string; } # end for VECTOR exit; # function(s) under test ########################################### sub classify { my ($string, ) = @_; # placeholder regexes. my $rx_valid = qr{ \A " [^"\\]* (?: \\. [^"\\]* )* " \z + }xms; my $rx_close_the_string = qr{ .* }xms; # always true for developm +ent my $rx_invalid_char = qr{ .* }xms; my $rx_invalid_scape = qr{ .* }xms; return $string =~ $rx_valid ? 'Valid String' : $string =~ $rx_close_the_string ? 'Close the string!' : $string =~ $rx_invalid_char ? 'Invalid char' : $string =~ $rx_invalid_scape ? 'Invalid escape' : die "unclassifyable string ", pp $string ; } # end sub classify()

Update: Also see How to ask better questions using Test::More and sample data.


Give a man a fish:  <%-{-{-{-<