in reply to Re: Regex Substitution, Interpolating on the RHS?
in thread Regex Substitution, Interpolating on the RHS?

That's very smart and I'm very grateful. Can I spoil all that for asking how I get a generalised solution where I can have the same code run both evaluated and non-evaluated regexes?

How do I code, for instance, so that $regex may sometimes be:

my $regex = ['(foo)',sub {\"bar$1"}];
but at other times just
my $regex = ['foo','bar'];

I'm guessing I'll need to use ref() or something?



($_='kkvvttuu bbooppuuiiffss qqffssmm iibbddllffss')
=~y~b-v~a-z~s; print

Replies are listed 'Best First'.
Re^3: Regex Substitution, Interpolating on the RHS?
by Roy Johnson (Monsignor) on Jul 19, 2005 at 13:20 UTC
    Yes, you would check ref($regex->[1]). It will be 'CODE' for a coderef and false (empty) for a non-ref. You could put the whole test/selection into the block like so:
    my $regex = ['(foo)',sub {\"bar$1"}]; my $string = 'blah foo blah'; $string =~ s/$regex->[0]/${(ref($regex->[1]) eq 'CODE' ? $regex->[1]-> +() : \$regex->[1])}/; print "S=$string\n";

    Caution: Contents may have been coded under pressure.