in reply to Variable assignment confusion
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Variable assignment confusion
by Aristotle (Chancellor) on Dec 15, 2003 at 20:28 UTC |