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

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.

Replies are listed 'Best First'.
Re^3: surprised to find cannot assign s/../../ to a variable
by Danny (Chaplain) on Jul 05, 2024 at 13:31 UTC
    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/;

      🦛

        It's not always need substitution, just matched parts will do, sometimes substitution make it simple. for like s/\.^.+$//r just like /(.*?)(?:\.^.*)$/
Re^3: surprised to find cannot assign s/../../ to a variable
by LanX (Saint) on Jul 06, 2024 at 13:04 UTC
    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