If you're certain you won't get invalid data, but only either four digits or else four digits, an underscore, and three digits, then using length or index or substr may be simpler than using a regex.

$short = "1234"; $result_1 = $short; $result_1 .= "_001" unless ( 4 < length $result_1 ); $result 2 = $short; $result_2 .= "_001 unless ( substr( $result_2, 4, ) ); $result 3 = $short; $result_3 .= "_001 unless ( index( $result_3, '_', 4) );

index is probably the fastest and most direct; if simply has to locate and return the fifth character,character number four, if there is one. substr returns the remainder of the string, starting after the fourth character, assuming that isn't past the end of the string. length has to count every character in the string. All of these are quite direct. Personally, I would use length, or maybe index.

If it's important to you to use one line, all of these could be used as the condition in a ternary expression, but two lines is clearer, in my opinion. I like to stretch ternaries over three lines, unless they are very simple:

$result_4 = $short . ( index( $short, 4, 1 ) ) ? "" : "_001";

--
TTTATCGGTCGTTATATAGATGTTTGCA


In reply to Re: Variable assignment confusion by TomDLux
in thread Variable assignment confusion by sweetblood

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.