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

I want to create a simple regular expression that finds a certain ord() in a string and converts it to another character:

$string =~ s/ord(226)/'/ig;

But perl is interpreting the 'ord(226)' as a literal.

How do I use ord() in a regular expression? Thank you!

  • Comment on Using 'ord' in a regular expression for substitution

Replies are listed 'Best First'.
Re: Using 'ord' in a regular expression for substitution
by Corion (Patriarch) on Aug 25, 2010 at 15:03 UTC

    ord doesn't work that way at all, and regular expressions don't either.

    Maybe you want this:

    my $to_replace = chr(226); $string =~ s/\Q$to_replace/'/gi;
Re: Using 'ord' in a regular expression for substitution
by ikegami (Patriarch) on Aug 25, 2010 at 15:29 UTC
    my $char = chr(226); my $pat = quotemeta($char); # Create pattern that matches string s/$pat/'/ig;
    my $char = chr(226); s/\Q$char\E/'/ig; # Alternate way of calling quotemeta
    s/\xE2/'/ig; # 0xE2 == 226
Re: Using 'ord' in a regular expression for substitution
by jwkrahn (Abbot) on Aug 25, 2010 at 15:24 UTC

    You don't really need to use a regular expression:

    $string =~ tr/\342/'/;

    But if you really want to:

    $string =~ s/\342/'/g;
      There is a difference. The OP uses /i. If $string has the UTF-8 flag set both â and  will match $r = chr 226; s/$r/'/ig;. And if UTF-8 isn't set, there still may be a locale that plays a role.
Re: Using 'ord' in a regular expression for substitution
by JavaFan (Canon) on Aug 25, 2010 at 15:04 UTC
    Uhm, ord is used to get the code point number given a single character string. Perhaps you mean chr?
    s/${\(chr(226))}/'/ig;
    But there's a simpler way. 226 decimal is E2 in hex:
    s/\x{E2}/'/ig;
Re: Using 'ord' in a regular expression for substitution
by roboticus (Chancellor) on Aug 25, 2010 at 15:07 UTC

    You don't. Try instead:

    # Build a regular expression: my $regex = qr/ord(226)/i; # Use it to alter $string: $string =~ s/$regex/'/g;

    Having said that, I doubt you want to use ord, as it converts a character into a number. I suspect you want chr which turns the number into a character...

    Update: Ignore this stupid post, please.

    ...roboticus

      What makes you think that $r = qr/STRING/i; s/$r/REPL/g; would work where s/STRING/REPL/ig; doesn't?

      qr/ord(226)/ fails in exactly the same way s/ord(226)/'/ig; does. Both match "ord226" and set (if matched) $1 to 226.