SPUG: auto-increment mixed alpha-numeric
Yitzchak Scott-Thoennes
sthoenna at efn.org
Fri Mar 14 01:21:03 CST 2003
On Thu, 13 Mar 2003 11:01:42 -0800 (PST), wildwood_players at yahoo.com wrote:
>auto-increment works fine for all alpha and all
>numeric and in some cases with a mix of alpha-numerics
>but not when a numeric precedes an alpha. In those
>cases I get two types of results. (e.g. '1AA' becomes
>2, 'A1A' becomes 1, then 2).
perlop says:
If, however, the variable has been used in only string contexts
since it was set, and has a value that is not the empty string and
matches the pattern C</^[a-zA-Z]*[0-9]*\z/>, the increment is done
as a string, preserving each character within its range, with carry
>Anyone have a simple solution to this? I will
>continue to look around and try things but I thought I
>would ask the community before any more time slipped
>away.
Perl's string-increment only fits a very narrow range of problems.
If you need anything outside that range, you pretty much have to
brew your own function.
Here's one that allows any mix of alpha and numeric:
sub string_inc {
die "whoops! bad input: $_[0] " if $_[0] =~ tr/a-zA-Z0-9//c;
my @in = split //, $_[0];
my $carry = 1;
for (reverse @in) {
++$_;
$carry = substr($_, 0, -1, ''); # remove all but last character
last unless length($carry);
}
$_[0] = join '', $carry, @in;
}
This may or may not be what you want. It acts like perl's string increment
(because it uses it) in ways that may not be applicable to your situation:
1) each position is either a digit or a number. 9 will increment to 0
with carry to the preceding character, z to a, and Z to A.
2) if fed a string consisting of only z, Z, and 9's, it inserts a new
first character of a, A, or 1, depending on the type of the
original first character.
3) Incrementing an empty string produces "1".
More information about the spug-list
mailing list