Have an idea?

Visit Sawtooth Software Feedback to share your ideas on how we can improve our products.

Random string generator?

Was hoping to generate a user id in the survey. Tried using some Perl script I found online but Sawtooth wouldn't execute the script. Is there a way to create a random string using specified characters in Sawtooth rather than just numbers using RAND() . I suppose I can select characters from an array of characters and JOIN them...was hoping for something less elaborate :)

Thanks!
asked Jan 19 by Chris Guth Bronze (1,380 points)

1 Answer

+1 vote
 
Best answer
Did the script you tried include this by chance?

use String::Random;


Using pre-built modules when possible is generally a good rule in programming, but it can be tricky to work with in Lighthouse Studio as the code will only work if the current environment (local for Test Survey, Sawtooth servers for official hosting, or another environment if self-hosting) has the module installed.  If you're comfortable with testing and potentially installing modules, that's great; otherwise, I usually stick with solutions that don't involve anything third-party modules.

For your situation, that solution would probably be just what you described.

[% Begin Unverified Perl
# Params
my @chars = ('a'..'z', 'A'..'Z', '0'..'9');
my $length = 8;

# Run
my $out;
for (my $i = 0; $i < $length; $i++) {
    $out .= $chars[rand(@chars)];
}
return $out;
End Unverified %]
answered Jan 19 by Zachary Platinum Sawtooth Software, Inc. (164,025 points)
selected Jan 19 by Chris Guth
lol..yes it was using  "use String::Random;"  I did more seraching and found something that worked similar to what you proposed. Thanks for the quick response. Your code looks cleaner so I'm gonna go with that :)

Thanks!

[code]
sub generate_random_string
{
    my $length_of_randomstring=shift;# the length of
             # the random string to generate

    my @chars=('a'..'z','A'..'Z','0'..'9','_');
    my $random_string;
    foreach (1..$length_of_randomstring)
    {
        # rand @chars will generate a random
        # number between 0 and scalar @chars
        $random_string.=$chars[rand @chars];
    }
    return $random_string;
}

#Generate the random string
my $random_string=&generate_random_string(11);
[\code]
...