SPUG: Petty perl obfuscation question

David Innes davidinnes at chicagoscience.com
Sat Oct 12 02:57:56 CDT 2002

So I'm a slow learner who's just started writing modules.  Hey, they're
Since all my work is usually embedded in IIS/ASP HTML I've always tried
to keep my stuff moderately readable.  Now that I can hid a bunch of my
stuff in modules where only I'll see it I'm starting to play with

I've gotten this function down to two lines and I'm wondering if it can
be gotten down to one.  It doesn't need to be one, but this is Perl so
why not try?

Here's the deal.  My function gets a string that has an arbitrary-length
prefix and a string of arbitrary length composed of two-character tokens
of the form Digit/Character.  The prefix is always separated from the
token with a hyphen.  The function separates the tokens from the prefix
string, sorts the tokens, and then returns the re-concatenated prefix
with it's now-sorted set of tokens.  

So it started out as...

#Define two subroutines
sub TokenSorter { #Verbose version
	$String = shift;
	my ($Prefix, $Tokens) = ( $String =~ m/^(..*-)(..*)$/ );
	my @Tokens = ($Tokens =~ /([0-9][A-Z])/ig); #pull out tokens
	@Tokens = sort @Tokens;
	$Tokens = join('', @Tokens);
	$String = $Prefix . $Tokens;
	return ($String);

#I've managed to shorten all this down to...

sub ShorterTokenSorter { #Two line version
	my ($Prefix, $Tokens) = (shift =~ /^(..*-)(..*)$/);
	return ($Prefix . join('', sort($Tokens =~ /([0-9][A-Z])/ig)));

#Display the output
print TokenSorter("Prefix-3C2B1A") . "\n";
print ShorterTokenSorter("Prefix-3C2B1A") ."\n";

I think I ought to be able to collapse this into one line where I return
$Prefix concatenated with some kind of gruesomely manipulated mess
instead of the $Units variable.  But I don't know how.

I'm actually happy with what I've got so this is a purely academic
question.  Thanks for your help.

		-- David Innes

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
     Seattle Perl Users Group (SPUG) Home Page: http://seattleperl.org

More information about the spug-list mailing list