in reply to regex incorrectly matching newline

What's in $i? It should work fine (and does for me) when $i eq "\n".
$rhs .= "hello"; $i = "\n"; if ($i =~ m/[ -~]/) { $rhs .= $i; } else { $rhs .= "."; } $rhs .= "world"; print("$rhs\n"); # Prints: hello.world

You regexp reads as "contains a valid char". Maybe you need one of the following (equivalent to each other) regexps.
$i !~ m/[^ -~]/     # Doesn't contain invalid chars
$i =~ m/^[ -~]*\z/  # Only contains valid chars

Replies are listed 'Best First'.
Re^2: regex incorrectly matching newline
by bfdi533 (Friar) on Jun 23, 2006 at 18:46 UTC

    Well, after you asked the question I looked back at the code and found it actually looked like the follow (more code context included):

    $buf = "hello\nworld"; $l = length($buf); for ($x = 0; $x < $l; $x++) { $piece = substr($buf, $x, 1); $i = ord($piece); if ($i =~ m/[ -~]/) { $rhs .= $i; } else { $rhs .= "."; } }

    So, the error is actually mine and works fine when using the right variable, $piece, as:

    if ($piece =~ m/[ -~]/)

    Sorry for the wasted space to post this question.

      No problem. Of course, you could simplify your entire code down to:

      $buf = "hello\nworld"; $buf =~ s/[^ -~]/./g; $rhs .= $buf;

      The above alters the value of $buf in the process. Feel tree to make a copy of $buf and work with the copy if you want to preserve $buf's value.