in reply to Re^2: surprised to find cannot assign s/../../ to a variable
in thread surprised to find cannot assign s/../../ to a variable

Maybe you need two options? $options{pattern} = some-pattern; $options{replacement} = some-replacement
my $pattern = defined $options{pattern} ? qr{$options{pattern}} : $def +ault_pattern; my $replacement = defined $options{replacement} ? $options{replacement +} : $default_replacement; $text =~ s/$pattern/$replacement/;

Replies are listed 'Best First'.
Re^4: surprised to find cannot assign s/../../ to a variable
by hippo (Archbishop) on Jul 05, 2024 at 13:40 UTC

    That looks like a sensible approach. If you have a perl released in the last decade and a half you can use defined-or to shorten the syntax too:

    use 5.010; my $pattern = $options{pattern} // $default_pattern; my $replacement = $options{replacement} // $default_replacement; $text =~ s/$pattern/$replacement/;

    🦛

      It's not always need substitution, just matched parts will do, sometimes substitution make it simple. for like s/\.^.+$//r just like /(.*?)(?:\.^.*)$/

        m// and s/// are two completely different operators. Do not try to shoehorn them into a single expression like that - you will just be creating less maintainable code. The best solution is not always the one with fewest keystrokes.

        if ($some_condition) { ($foo) = ($bar =~ m/capturing_pattern/); else { ($foo = $bar) =~ s/pattern/replacement/; }

        That should hopefully be unambiguous and more maintainable than the original proposal.


        🦛