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

I find myself doing things like this a lot: (assuming I want to keep $string unaltered)

$string = "blah foo blah"; . . . $tmp = $string; $tmp =~ s/foo/blah/; use($tmp);
Is there a cleaner way to do that, preferably without having to use a temporary variable each time?

---
A fair fight is a sign of poor planning.

Replies are listed 'Best First'.
Re: Non-destructive substitution?
by Abigail (Deacon) on Jul 03, 2001 at 01:16 UTC
    You cannot avoid using a different variable.

    The usual idiom is:

    ($tmp = $string) =~ s/foo/blah/;
    If you want to combine it with calling a function, use Perls do:
    func do {(my $tmp = $string) =~ s/foo/blah; $tmp};
    Or
    func do {local $_ = $string; s/foo/blah; $_};

    -- Abigail

      Such a shame too, it would be nice if there were a "return substituted copy" modifer for s///, would make alot of golfs shorter :)
         MeowChow                                   
                     s aamecha.s a..a\u$&owag.print
Re: Non-destructive substitution?
by epoptai (Curate) on Jul 03, 2001 at 01:17 UTC
    There is a cleaner way, but you still need the temporary variable to preserve $string. I assume you need $string later which is the only reason you'd need a non-destructive substitution. You can declare and substitute in one step:
    (my$tmp = $string) =~ s/foo/blah/;

    --
    Check out my Perlmonks Related Scripts like framechat, reputer, and xNN.

Re: Non-destructive substitution?
by CharlesClarkson (Curate) on Jul 03, 2001 at 08:02 UTC

    A similar question was answered on c.l.p.misc in May. The solution is not mine, but I present it here.

    Wanted: function composition using tr, s, etc. operators:

    $var2 = s/123/456/g (tr/a-z/A-Z/ ($var));
    The answer:
    sub apply (&$) { local $_ = $_[1]; $_[0]->(); $_; } $var2 = apply {s/123/456/g; tr/a-z/A-Z/} $var;
    or in this case:    $string = apply {s/foo/blah/} $string;

    HTH,
    Charles K. Clarkson
      I am not sure that this function "apply()" is shorter or more usefull than a temporary variable... :)

      BobiOne KenoBi ;)

        Probably not, but it may be what was requested: "a cleaner way to do that, preferably without having to use a temporary variable each time".

        TIMTOWTDI,
        Charles K. Clarkson