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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.