Hello fellow monks!
After a long ( and now semi permanent ) exile from computing I present a subroutine which will populate an array with all possible case permutations of a word which is supplied to it. I consider it an elegant solution to something which originally was a recursive broken monstrosity.
Recursion is evil.
sub casify
{
my @arr = ();
my $word =lc $_[0];
my $maxcombos = 2**(length $word) - 1;
foreach $n ( 0..$maxcombos )
{
# convert number from being stringified, to being a u_short, and then
+into binary
$_ = unpack( 'b*', pack('s',$n) );
tr/1/_/; # uppercase ones
tr/0/\377/; # leave zeros alone
$result = "$word" & $_; # string AND
push( @arr, $result ) ;
}
return @arr;
}
#--------------------------------------------------
# fast casify(), first arg word ref, second arg arr ref
sub casify_fast
{
foreach $n ( 0..(2**(length ${$_[0]}) - 1) )
{
# convert number from being stringified, to being a u_short, and then
+into binary
$_ = unpack( 'b*', pack('s',$n) );
tr/10/_\377/;
push( @{$_[1]}, ("${$_[0]}" & $_) ) ; # string AND them, ones up
+percase the letters, zeros don't
}
return;
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|