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

I'm sure this can be done, it just escapes me what the exact syntax is. I would like to modify a set of variables by one regex command. How can I do this? I've seen it done with a shortcut for plain assignment:
$var1 = $var2 = $var3 = 0;
How can this be done for the following with regex search/replace?
$var1 =~ $var2 =~ s/\n/<br>/g;
Thank ya!

blackjudas

Replies are listed 'Best First'.
Re: Multiple variable assignments with RexExp
by FoxtrotUniform (Prior) on May 21, 2002 at 20:29 UTC

    I've never seen it done that way. My approach would be a bit more idiomatic and (probably) easier to read, but the mechanism's a tiny bit obscure:

    s/\n/<br>/g foreach ($var1, $var2);

    --
    :wq

Re: Multiple variable assignments with RexExp
by particle (Vicar) on May 21, 2002 at 20:56 UTC
    perl 6 hyper-operator, anyone?

    ($var1, $var2) ^=~ s/\n/<br>/g;
    i think this will be the idiom in the near future. i can't wait!

    ~Particle *jonesin' for perl 6*

Re: Multiple variable assignments with RexExp
by Zaxo (Archbishop) on May 22, 2002 at 03:58 UTC

    Here's a somewhat heretical solution:

    map {s/\n/<br\/>/g} $var1, $var2;
    Yes, map in void context. It is acting as an operator, modifying its arguments as do chomp, splice, and others. The substution acts on $_ which is, in map's codeblock, an alias to the current list argument This won't work for constant arguments, of course.

    Go ahead and assign from it if you need statistics on the number of substitutions. The style campaign against map in void context makes the device all the more helpful at calling attention to using map for side effects.

    After Compline,
    Zaxo

      Map in a void context! Bad Zaxo! :-)

      I cannot fathom why you would take this approach when the following would be much clearer and avoid the building of a list return which is being discarded:

      s/\n/<br\/>/g for $var1, $var2;

      Note too, that this isn't a "style" issue, but one of using the best function for a given task - Yes, map does fit the task here, however it is only the loop function of map which you are making use of, not the list return, a function better suited to a for or foreach loop.