Front page | perl.perl5.porters |
Postings from January 2014
Re: Slowest JAPH ever?
Thread Previous
From:
Brad Gilbert
Date:
January 4, 2014 16:26
Subject:
Re: Slowest JAPH ever?
Message ID:
CAD2L-T3cLbTDvoeiX+qPDkzp44OqCmPLR2ETpdbEEzninb1qUQ@mail.gmail.com
On Sat, Jan 4, 2014 at 8:32 AM, Father Chrysostomos <sprout@cpan.org> wrote:
> $|=1;
> sub word($) {
> my $x = "a";
> for (1..shift) { $x++ }
> $x
> }
> print ucfirst word 190469;
> print " ";
> print lcfirst word 482466755;
> print " ";
> print ucfirst word 285075;
> print " ";
> print lcfirst word 95568295;
> print ",\n";
>
There is a much faster version, that uses _num_to_alpha()
from t/test.pl in the repository.
sub _num_to_alpha; # so that we can remove ()
do 't/test.pl';
$|=1;
print ucfirst lc _num_to_alpha 190469;
print " ";
print lcfirst lc _num_to_alpha 482466755;
print " ";
print ucfirst lc _num_to_alpha 285075;
print " ";
print lcfirst lc _num_to_alpha 95568295;
print ",\n";
So that you don't have to look for it in the file; here it is in all it's glory:
# _num_to_alpha - Returns a string of letters representing a positive integer.
# Arguments :
# number to convert
# maximum number of letters
# returns undef if the number is negative
# returns undef if the number of letters is greater than the maximum wanted
# _num_to_alpha( 0) eq 'A';
# _num_to_alpha( 1) eq 'B';
# _num_to_alpha(25) eq 'Z';
# _num_to_alpha(26) eq 'AA';
# _num_to_alpha(27) eq 'AB';
my @letters = qw(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z);
# Avoid ++ -- ranges split negative numbers
sub _num_to_alpha{
my($num,$max_char) = @_;
return unless $num >= 0;
my $alpha = '';
my $char_count = 0;
$max_char = 0 if $max_char < 0;
while( 1 ){
$alpha = $letters[ $num % 26 ] . $alpha;
$num = int( $num / 26 );
last if $num == 0;
$num = $num - 1;
# char limit
next unless $max_char;
$char_count = $char_count + 1;
return if $char_count == $max_char;
}
return $alpha;
}
Since this sub is only for tempfile() it has a feature to return undef
if the length would be over a certain length.
Thread Previous