in reply to surprised to find cannot assign s/../../ to a variable

qr is meant for regexes only, s/// is a complex command where only the left part is a regex, see also m//

For storing complex code use a subroutine.

DB<6> sub repl { $_[0] =~ s/a/b/ } DB<7> p $a aa DB<8> repl $a DB<9> p $a ba

Tho your motivation is unclear for me , smells like an XY problem

Cheers Rolf
(addicted to the Perl Programming Language :)
see Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re^2: surprised to find cannot assign s/../../ to a variable
by vincentaxhe (Scribe) on Jul 05, 2024 at 13:08 UTC
    I was try to write
    my $namematch = defined $options{r} ? qr($options{r}) : qr{s/\.[^.]+$/ +/r}; my @name = $file =~ $namematch;
    now I have to write this
    my $namematch = qr($options{r}); my @name = defined $options{r} ? $file =~ $namematch : $file =~ s/(\.[ +^.]+)+$//r;
    there will be many cases I donot want write substitudion code dead in the script.
      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/;

        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/;

        🦛

      As I said

      > > For storing complex code use a subroutine

      > > sub repl { $_[0] =~ s/a/b/ }

      Hence...

      DB<9> %options = ( r => sub { $_[0] =~ s/(a)/A/gr } ) # r is set DB<10> x @name = $options{r}->('abc') 0 'Abc' DB<11> $options{b} //= sub { $_[0] =~ s/(b)/B/gr } # b defaulted if + undefined DB<12> x @name = $options{b}->('abc') 0 'aBc' DB<13> $options{r} //= sub { $_[0] =~ s/(b)/B/gr } # r exists DB<14> x @name = $options{r}->('abc') 0 'Abc' DB<15>

      Your use of a list assignment to @name in combination with /r looks wrong tho

      Anyway, welcome in the world of functional programming

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      see Wikisyntax for the Monastery