Here's a quickie: this came up on perl5-porters yesterday: someone filed what they thought was a bug, but was bitten by the fact that a capture that does not match returns undef, rather than the empty string. One way around it is to just switch of warnings when substituting values containing undef:
use strict; use warnings; use Test::More tests => 6; is(munge('R'), 'text', 'R'); is(munge('R1'), '1text', 'R1'); is(munge('R2'), '2text', 'R2'); is(munge('R3'), 'text3', 'R3'); # this here is the trickiness is(munge('R13'), 'R13', 'R13 unchanged'); is(munge('R4'), 'R4', 'R4 unchanged'); sub munge { my $str = shift; no warnings; $str =~ s/^R(?:([12])|(3))?$/${1}text$2/; $str; }
Another alternative, even more icky in my books, is to say:
sub munge { my $str = shift; $str =~ s{^R(?:([12])|(3))?$} {(defined $1 ? $1 : '') . 'text' . (defined $2 ? $2 : '') +}e; $str; }
So I ask the monks... is there an elegant (clean, simple) way to do the substition without /e or no warnings? Note that the real tokens R, 1, 2... in real life are meta characters, so substr is ruled out, it must be a regexp, and so one just needs to make sure that $1 and $2 are always strings, empty or otherwise.
• another intruder with the mooring in the heart of the Perl
In reply to Dealing with undefined captures in a substitution by grinder
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |