Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am not allowing certain characters to be entered into a specific field, so I check it like this:
my $_field1 = $in{other_state}; if($_field1 =~ /[^A-Za-Z0-9\.\, ]+/) { my $_field1Check = $_field1; $_field1Check =~ s/[^A-Za-Z0-9\.\, ]+//g; }
Ok, that would then strip those characters that were not in the check I did. How could I get $_field1Check to not have the field that is acceptable, rather have the left the ones that are NOT acceptable so I can show the user?

For instance if they entered:

Some Other - State & Non State
then I would want it to show each of the invalid ones:
-
&
so they would know which characters resulted in the error.

Thanks for any help you can offer.

Rich

Replies are listed 'Best First'.
Re: getting stripped characters from string
by AnomalousMonk (Archbishop) on Nov 10, 2010 at 22:21 UTC

    One way:

    >perl -wMstrict -le "my $ok = 'a-zA-Z0-9., '; ;; my $string = 'foo - bar & baz & boff'; ;; (my $all_ok = $string) =~ s{ [^$ok] }{}xmsg; (my $all_bad = $string) =~ s{ [$ok] }{}xmsg; ;; print qq{these are ok: '$all_ok'}; print qq{these are bad: '$all_bad'}; " these are ok: 'foo bar baz boff' these are bad: '-&&'

    Note that
        my $ok = 'a-zA-Z0-9., ';
    appears in single quotes so that something like  \d (which is perfectly valid in a character class) will not be interpolated as a single literal 'd'.

Re: getting stripped characters from string
by aquarium (Curate) on Nov 10, 2010 at 23:37 UTC
    typically one would not pin-point or otherwise tell the user exactly what is wrong with the input. either restrict the character set in the input (i.e. per keystroke) or just tell them it's not valid and what the valid characters are. unless that's the whole point of the application.
    the hardest line to type correctly is: stty erase ^H
Re: getting stripped characters from string
by Anonymous Monk on Nov 10, 2010 at 22:19 UTC
    Remove the ones acceptable. Then, what's left is the ones not acceptable...
      or, more fancily, record what you replaced (e.g. in a hash, together with the character positions):

      #!/usr/bin/perl -wl use strict; my $_field1 = 'Some Other - State & Non State'; my %invalid; $_field1 =~ s/([^A-Za-z0-9\.\, ])/push @{$invalid{$1}}, pos($_field1); + ''/ge; print "invalid char '$_' at pos @{$invalid{$_}}" for sort keys %invali +d; print "cleaned input: '$_field1'"; __END__ invalid char '&' at pos 19 invalid char '-' at pos 11 cleaned input: 'Some Other State Non State'
Re: getting stripped characters from string
by 7stud (Deacon) on Nov 11, 2010 at 00:29 UTC

    Hopefully, you are doing an initial check with javascript so that you don't clog up your server with such mundane tasks?

    Note that inside a character class, [], you don't need to escape dots, etc.--they have their literal meaning.

    Also note the typo inside your character class: a-Z.