Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Riddle with regex (updated)

by AnomalousMonk (Archbishop)
on Nov 07, 2020 at 17:51 UTC ( [id://11123474]=note: print w/replies, xml ) Need Help??


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:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11123474]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-04-19 04:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found