... a generic function to simulate /r ...
Defining functions that take 'naked' subroutine blocks is, IMHO, one of the few valid reasons for using prototypes. However, there's a subtle pitfall here that belies the word 'generic' in the description of the function. The use of the $ prototype causes behavior that will almost certainly cause puzzlement in a wider, i.e., more generic, context by imposing scalar context on its argument. Better, I think, to use @ instead.
>perl -wMstrict -le
"sub rx (&$) {
my $c_regex = shift;
local $_ = shift;
$c_regex->();
return $_;
}
;;
my $s = 'a b c';
print rx { s/ /_/g } $s;
;;
my @ra = 'p q r';
print rx { s/ /_/g } @ra;
"
a_b_c
1
>perl -wMstrict -le
"sub rx (&@) {
my $c_regex = shift;
local $_ = shift;
$c_regex->();
return $_;
}
;;
my $s = 'a b c';
print rx { s/ /_/g } $s;
;;
my @ra = 'p q r';
print rx { s/ /_/g } @ra;
"
a_b_c
p_q_r