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

/me kneels before the Perl monks...

After asking the resident Perl geeks, I turn to you for wisdom. What is the Right Way to use a variable as a basis for an s///, without modifying it?
$foo = "bar baz"; (my $qux = $foo) =~ s/bar/quux/;
Here $foo is unchanged, and $qux equals "quux baz". Is there a more elegant way to do this, e.g. without first copying $foo?

(BTW, brother dep informs me that using 'my' inside of the parentheses is not a good thing. Maybe that's why I insist on doing it that way... ;] What traps can I run in to doing that?)

Replies are listed 'Best First'.
Re: Substituting without modifying
by chipmunk (Parson) on May 20, 2001 at 21:19 UTC
    If I understand your question... You want to perform a substitution on the value in $foo, without changing the value of $foo or copying the value to another variable first?

    I think that you will be able to meet any two of those three requirements. :)

    Here's something to consider, although it requires $foo to be a package variable rather than a lexical, and still involves copying the value:

    $foo = "bar baz"; { (local $foo = $foo) =~ s/bar/quux/; # do something with the modified $foo } # now the original $foo is back again
    BTW, there is nothing wrong with your use of my inside the parentheses.
      Your method works great using lexical variables as well, because the perl interpreter correctly interpolates the temporary value of $foo when that temporary value is in scope.
      use strict; my $foo = "bar baz"; { (my $foo = $foo) =~ s/bar/quux/; # do something with the modified $foo $foo = "changed it"; print "The temporary value of foo is $foo.\n"; } # now the original $foo is back again print "The original value of foo is $foo.\n";
      Running under ActiveState 5.6.1 and Windows ME, the above code first returns the temporary value of "changed it" and then the original value of "bar baz".
Re: Substituting without modifying
by chromatic (Archbishop) on May 21, 2001 at 00:57 UTC
    That's syntactically equivalent to a two-step operation:
    my $qux = $foo; $qux =~ s/bar/quux/;
    It just takes one line of code, so it's more idiomatic. There's absolutely nothing wrong with it, and I quite like it myself. There are only two things you might run into -- programmers who don't understand the idiom, and the looks of a my inside braces.

    If it makes your life easier, go for it.

Re: Substituting without modifying
by lemming (Priest) on May 20, 2001 at 22:30 UTC
    That is a method right out of the camel. You have to use the parentheses, otherwise $qux would have the number of times the pattern matched and $foo would be changed. Nothing wrong with my in my opinion