On Mon, 21 Mar 2005 18:44:52 +0530, Ramprasad A Padmanabhan wrote:
> Hello All
> I want to remove all characters with ascii values > 127 from a string
> 
> Can someone show me a efficient way of doing this.
> Currently what I am doing is reading the string char-by-char and check
> its ascii value. I think there must be a better way.
> 
> Thanks
> Ram
> 

$string =~ s/(.)/(ord($1) > 127) ? "" : $1/egs;

Overview:
* For every ("g") char(".") (saved in $1), if its numeric code is >
127, replace it with an empty string, otherwise leave it alone.

Explanation:
* if the string to be modified is saved in $string, than:
    $string =~ s/(.)/EXPR/g;
   will replace every character in $string with EXPR, due to the "g" modifier.
* Since I'm using the "e" modifier as well, EXPR is taken to be Perl
code, which is evaluated (think as "e" as short for "eval"), and the
value it returns is used for the substitution. It basically means
means writing an inline subroutine that returns the value you want,
depending on the current char (which was saved in $1).
* See "perldoc -f ord" for an explanation of the ord() function, and
"perldoc perlop" for an explanation of the ?: "Conditional Operator".
* The "s" modifier is just an extra precaution on my side - if you
have embedded newlines in your string, "." will not match them, unless
you use the "s" modifier. Actually in this case it is not really
needed, I guess.

Hope this helps,
-- 
Offer Kaye

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to