Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Filtering unwanted chars from input field

by Kenosis (Priest)
on Dec 17, 2012 at 19:04 UTC ( #1009222=note: print w/ replies, xml ) Need Help??


in reply to Filtering unwanted chars from input field

I agree with CountZero. One implementation of this can be:

use strict; use warnings; print filter($_), "\n" for <DATA>; sub filter { my $str = shift; defined $str or return ''; my $acceptable = 'a-z0-9_.'; $str =~ s/[^$acceptable]//gi; return $str; } __DATA__ Hello, world! te-st%$/*. All_of_this_is_OK. !@#$%^&*()12345

Output

Helloworld test. All_of_this_is_OK. 12345

Edit: Used a simpler s///


Comment on Re: Filtering unwanted chars from input field
Select or Download Code
Replies are listed 'Best First'.
Re^2: Filtering unwanted chars from input field
by johngg (Abbot) on Dec 17, 2012 at 21:02 UTC

    Instead of spliting and greping it might be simpler to use tr (see Quote and Quote like Operators).

    $ perl -E ' > @data = ( > q{Hello, world!}, > q{te-st%$/*.}, > q{All_of_this_is_OK.}, > q{!@#$%^&*()12345}, > ); > say for map { tr{A-Za-z0-9_.}{}cd; $_ } @data;' Helloworld test. All_of_this_is_OK. 12345 $

    I hope this is of interest.

    Cheers,

    JohnGG

      Thank you, johngg. Not sure why I complicated it. Yours is, indeed, a more elegant and readable solution (++). Was brought back to this node after the following should-have-done-this-in-the-first-place solution occurred to me:

      $str =~ s/[^$acceptable]//gi;

      Edited my original comment to reflect this...

      Would I be breaking the law by allowing a "-" and updating the code to:
      sub filter { my $str = shift; defined $str or return ''; $str =~tr{A-Za-z0-9_.-}{}cd; return $str; }

        That will work ok.

        $ perl -E ' > @data = ( > q{Hello, world!}, > q{te-st%$/*.}, > q{All_of_this_is_OK.}, > q{!@#$%^&*()12345}, > ); > say for map { tr{A-Za-z0-9_.-}{}cd; $_ } @data;' Helloworld te-st. All_of_this_is_OK. 12345 $

        Cheers,

        JohnGG

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (17)
As of 2015-07-30 15:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (272 votes), past polls