Shawn H Corey wrote:
Yonghua Peng wrote:
--- On Tue, 24/11/09, Shawn H Corey <shawnhco...@gmail.com> wrote:

From: Shawn H Corey <shawnhco...@gmail.com>
Subject: Re: 答�: Regex to get last 3 digits of a number.
To: "gaochong" <zjgaoch...@gmail.com>
Cc: "'John W. Krahn'" <jwkr...@shaw.ca>, "'Perl Beginners'" <beginners@perl.org>
Received: Tuesday, 24 November, 2009, 8:26 PM
gaochong wrote:
But I think substr is better .

my $str="0000000000000111";
my $r=substr ($str,-3);
TimTowTdi (there is more than one way to do it):

my $n = "0000000000000111";
my $last_3_chars = join('',(split(//,$n))[-3..-1]);
The worst way, :-)
split is much slower than others.

Worst?  Hardly.  I'm just getting warmed up.

my $n = "0000000000000111";

my $last_3_digits = sprintf '%03d', $n - int( $n / 1_000 ) * 1_000;

Or:

my $last_3_digits = sprintf '%03d', $n % 1_000;


print "$last_3_digits\n";

my $fluff = length( $n ) - 3;
my $last_3_chars = (unpack "a$fluff a*", $n)[-1];

Or:

my $last_3_chars = unpack "x$fluff a*", $n;


print "$last_3_chars\n";


John
--
The programmer is fighting against the two most
destructive forces in the universe: entropy and
human stupidity.               -- Damian Conway

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to