I need to find the length of the first captured match from a regex. Normally, I might do this:
my $x = 'abc12345';
my ($y) = $x =~ /(\d+)$/;
my $length = length($y);
Being in a contrary mood, I wondered if I could do that in one statement, and tried this:
my $x = 'abc12345';
my $length = length ($x =~ /(\d+)$/);
# returns 1, the length of the number in the number of elements
I came up with this, but it wasn't satisfying:
my $x = 'abc12345';
my $length = map { length } ($x =~ /(\d+)$/);
(Yes, useles use of
map might deserve its own warning.)
To generalize for cases where there might be more matches (a variable in the regex, for example), I generalized to this:
my $x = 'abc12345';
my $length = map { length } ($x =~ /(\d+)$/)[0];
But that led me to this:
my $x = 'abc12345';
my $length = length (($x =~ /(\d+)$/)[0]);
# returns 5
Is there a better way to do this, or have I hit the practical limit?
-QM
--
Quantum Mechanics: The dreams stuff is made of
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.