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

Heya All,

Having some aggrevating difficulties with a small regex; here's hoping you'll be kind enough to shed some light on this trouble for me.
(my @values = $q->param($key)) =~ s/\cM//g;
The array @values holds multiple lines which are to be dumped to a flat file shortly after the above code snippet. I am trying to remove the *irritating* CR (^M) character from each line held within the array. Various attempts using modifications of the above code have proven to be fruitless. Advice as to where I stray is greatly appreciated.

Cheerio,
Lacertus

------------------------------------
"There is more in heaven and earth
than is dreamt of in your philosophy"

Replies are listed 'Best First'.
Re: Array regex matching
by Zaxo (Archbishop) on Jan 12, 2004 at 22:33 UTC

    You're trying to bind to an entire array, but that won't work. Take the elements one at a tine:

    my @values = $q->param($key); tr/\015//d for @values;

    After Compline,
    Zaxo

Re: Array regex matching
by ysth (Canon) on Jan 12, 2004 at 22:49 UTC
    Congratulations, you've found a bug in perl!

    s/// only works on one scalar at a time, so the right side of =~ gets scalar context (gets interpreted as a scalar). Because it is often convenient, a list assignment (what you have in parentheses) in scalar context results in the number of elements on the right side of the assignment.

    So if param() returns 27 values, you will be doing "27" =~ s/\cM//g; (except that gets a "Can't modify" error)

    In your case you should have gotten a "Can't modify list assignment in substitution (s///)" compile error. That you didn't is a bug in perl. I note that you can also say things like ++(my @v = foo()) which should also result in an error.

    Update: I meant to also say: the correct way to do what you intend is to loop over the array:

    my @values = $q->foo($key); s/\cM//g for @values;
    Update: spelling mistake
      This is a classic case of s///g being overkill. tr/\cM//d works just fine.

      The PerlMonk tr/// Advocate
Re: Array regex matching
by borisz (Canon) on Jan 12, 2004 at 22:29 UTC
    try this:
    my @values = map { s/\cM//g;$_ } $q->param($key);

    Update: abigail-II noticed that my example was wrong. So here is a updated node.

    Boris
      I bet you didn't test this. This will leave @values with a set of true/false values, depending whether a carriage return could be removed or not. If you want to use a map, do it like:
      map {s/\cM//g} my @values = $q -> param ($key);

      Abigail