Re: Extract last two digits from numbers
by Limbic~Region (Chancellor) on Jan 06, 2004 at 10:10 UTC
|
Anonymous Monk,
There are lot's of ways to do this - you might want to consider taking a look at perldoc perlre.
#!/usr/bin/perl -w
use strict;
my $number = 1234;
my $last2;
if ( $number =~ /^\d\d(\d\d)$/ ) {
$last2 = $1;
}
print "$last2\n" if defined $last2;
Cheers - L~R
Update: Regular expressions can be tricky as can be the notion of what constitutes a "number". You might also want to take a look at Mastering Regular Expressions and Scalar::Util's looks_like_number function for some more advanced stuff. | [reply] [d/l] |
Re: Extract last two digits from numbers
by tachyon (Chancellor) on Jan 06, 2004 at 10:10 UTC
|
my ($digits)= $str =~ m/\d\d(\d\d)/;
cheers
tachyon
| [reply] [d/l] |
Re: Extract last two digits from numbers
by CountZero (Bishop) on Jan 06, 2004 at 10:39 UTC
|
No need to use a regex:
$lasttwo=substr($number,-2,2)And it works for any length of number. It works even for non-numerical strings (Is that a bug or a feature?)
CountZero "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law
| [reply] [d/l] |
|
|
my $s= '12345';
print substr $s, -2;
45
Of course, it doesn't hurt either :)
Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
Hooray!
| [reply] [d/l] |
Re: Extract last two digits from numbers
by yosefm (Friar) on Jan 06, 2004 at 10:13 UTC
|
Assuming the number is at the end of the variable being matched, use: /\d{2}$/. the '\d' means match digits, the '{2}' means two exactly, and the '$' means end of line. Other option: /\d\d$/ (simpler).
Update: Note that L~R's regex is more specific (putting '^' first means start of line) while tachyon's regex is more relaxed, finding any 4 digit number and capturing its last two digits (using parentheses).
Another update: See L~R's reply below. | [reply] |
|
|
| [reply] |
|
|
| [reply] [d/l] |
|
|
Re: Extract last two digits from numbers
by BrowserUk (Patriarch) on Jan 06, 2004 at 11:13 UTC
|
If you know that your numbers are numbers, then there's no need to use a regex, just math.
my $number = '0234';
$number %= 100;
print $number;
34
Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
Hooray!
| [reply] [d/l] |
|
|
my $number = '3204';
$number %= 100;
print $number;
4
Abigail | [reply] [d/l] |
|
|
Good point. I guess it depends on whether the OP wants two characters or the numeric value of the last two digits.
Without clarification, my interpretation is probably the least likely given context.
Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
Hooray!
| [reply] |