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

How about:

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11160391 use warnings; # wanted #my $namematch = defined $options{r} ? qr($options{r}) : qr{s/\.[^.]+$ +//r}; #my @name = $file =~ $namematch; my $file = 'foobar.txt'; my %options = ( r => '(.{3})', other => '.{3}(.{3})' ); # case for defined { my $namematch = defined $options{r} ? sub { /$options{r}/ } : sub { s/ +\.[^.]+$//r }; my @name = map { $namematch->() } $file; print "defined case, \@name = @name\n"; } # case for not defined { %options = (); my $namematch = defined $options{r} ? sub { /$options{r}/ } : sub { s/ +\.[^.]+$//r }; my @name = map { $namematch->() } $file; print "not defined case, \@name = @name\n"; }

Outputs:

defined case, @name = foo not defined case, @name = foobar

Avoids the eval

Replies are listed 'Best First'.
Re^2: surprised to find cannot assign s/../../ to a variable
by vincentaxhe (Scribe) on Jul 06, 2024 at 06:11 UTC
    yeah,thanks. But refed subroutine cannot do all eval do. $options{r} did not mean I want pattern match only, I use substitution if it's simpler.