LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Help with perl script (https://www.linuxquestions.org/questions/linux-general-1/help-with-perl-script-436177/)

GUIPenguin 04-17-2006 06:38 PM

Help with perl script
 
Hello. This is my secound day learning perl. So I thought I would write a simple script to use an array and randomly choose one of the 26 availible letters which will be checked against what you wanted to find, then print how many times it took.

here is what I have to find one letter of your choosing.

Code:

#!/usr/bin/perl

@array=('A' .. 'Z' );

$times = 0;

while ($hold ne "A") {



        $randnum = int( rand(26) );

        $hold = @array[$randnum];

        $times++;

}

print("We found A! Tt took $times times \n");

Cool. This works fine for what I want. Now here is my question: How can I get this same model to work for a string of more then 1 letters.
For example, locating a string that is 2 letters, such as AB or ABC. Like maybe I would like to see how long it takes to randomly find my name 'JOHN'. Hope I provided enough info about how goal.

zaichik 04-17-2006 08:00 PM

Assuming you still want to find A, but want to generate random strings of random length from 1 to MAX_LEN characters, maybe something like this:
Code:

#!/usr/local/bin/perl
use strict;

my @array = 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/;
my $MAX_LEN = 5; # Maximum letters allowed in the string
my $times = 0;
my $x = 0; # counter
my $hold;
my $string_length;
my $randnum;

while ($hold ne "A") {
  $string_length = int( rand( $MAX_LEN - 1)) + 1; # if we want 1 - 5, get 0 - 4 and add one
  print "string_length = $string_length\n";
  $hold = "";
  for( $x = 0; $x < $string_length; $x++ ) {
      $randnum = int( rand( 25 )); # rand( x ) returns 0 to x; we only want 0 to 25 here, really

      $hold = $hold . @array[$randnum];
  }
  print "hold = $hold\n";
  $times++;
}

print("We found A! It took $times times \n");

I'm not 100% clear on what you are looking for, so if that's not it, please do clarify a tad. Hope that helps.

GUIPenguin 04-17-2006 09:07 PM

sweet. Thanks a ton. Im going to change it around a little bit to suit my needs and to give me a little better idea about how it works.

spooon 04-18-2006 02:34 AM

Actually, int(rand(x)) returns an integer from 0 to x-1

Also (because I am a picky Perl programmer), I will point out you can write that for loop with something like this:
Code:

$hold = join '', map $array[rand @array], (1..$string_length);


All times are GMT -5. The time now is 10:59 AM.