in reply to A Functional Substitute

What about:

($second = $first) =~ s/foo/bar/;

Replies are listed 'Best First'.
Re^2: A Functional Substitute
by mrborisguy (Hermit) on Aug 08, 2005 at 23:21 UTC

    This, and BrowserUk's suggestion are both good ones. BrowserUk's I wasn't even aware of, and this one I had somewhat forgot about. However, I do like the consistency of having one method of doing it that works both standalone and in map. Although I usually argue that adding a variable at the end of a map block isn't that bad, I'm going to be a devil's advocate and argue against it here.

    my @output = map { (my $i = $_) =~ s/foo/bar/; $i } @input;

    Seems less readable to me than

    my @output = map { $_ \~ s/foo/bar/ } @input;

    And I like the use of 'map' instead of 'filter' (especially since I think of grep when I think of filter).

    I guess it looks like personal preference here, so maybe I'll just perfect this one and keep it for myself (since I don't use $1 and $2 very often from what I've noticed, I wouldn't have to fix them just for myself).

        -Bryan

      map { $_ \~ s/foo/bar/ }
      I don't like that $_ there. Shouldn't you be able to do something like
      map { \s/foo/bar/ }
      so that it operates on $_ by default, implicitly?

        I had thought about this as well, or even making the entire syntax something like $x = $y =~ \s/foo/bar; or something of the sort. To be honest though, everything worked well when I posted this - and I didn't think I was actually parsing too much Perl on my own - but as I expanded, I realized what I wanted to - things like my $foo = sub_returns_string() \~ s/bar/foo/;1 just got too messy and needed too much parsing of Perl, so as much as I love this idea, I've dropped it - for now.

        1It seems like there's just increasing complexity to make it 'just work' like people would expect it to. Something like my $foo = subroutine( this => 'contains an equals', $self->{ scalar @array } ) =~ s/a/b/g; although probably would be rarely used, would still need to just work. So I'm really beginning to understand why people shy away from using source filters, because really there is a lot of parsing Perl, even for the simple thing like I wanted to do, where I thought I could isolate the problem and not have to do much.

            -Bryan