Jairo Jairo - 2 months ago 10
Perl Question

Use of inintialized value $ in concatenation (.) Perl

use warnings;

$a = 5;
$c = 3;
$i;
$x = time();
$m = 32;
$caracter_aleatorio;
@caracteres = (A..Z);
print "Ingrese la cantidad de letras que desea generar=> ";
$n = <STDIN>;

sub generadorMultiplicativo{
$numAleatorio = ((($a*$x) + $c) % $m);
$x = $numAleatorio;
}

for($i=1;$i<=$n;$i++){
&generadorMultiplicativo();
$caracter_aleatorio = $caracteres[$numAleatorio];
if($numAleatorio == 0){
$numAleatorio++;
}
if($numAleatorio > 26){
$numAleatorio = $numAleatorio - 5;
}

print"Letra #$i = $caracter_aleatorio\n";
}
<>;


I know this warning is when the variable doesn't have a value, but I´ve tried everything but it´s the same, it´s a generator of "random" letters.

Could you help me?

Answer
  1. Always use strict when writing new code.
  2. Uninitialized warnings means that your $caracter_aleatorio variable is undefined, so you should set a default. Undefined variables are usually a sign of buggy code.
  3. Declare your variables using my
  4. One-letter variables should be avoided for maintenance / readability reasons.
  5. No-longer need to call functions with &foo() notation, foo() is fine.
  6. Use quotes around A and Z to generate the range.

Here is an updated version of your code:

use strict;
use warnings;

my $a = 5;
my $c = 3;
my $i;
my $x = time();
my $m = 32;
my $caracter_aleatorio;
my $numAleatorio;
my @caracteres = ('A'..'Z');
print "Ingrese la cantidad de letras que desea generar=> ";
my $n = <STDIN>;

sub generadorMultiplicativo{
    $numAleatorio = ((($a*$x) + $c) % $m);
    $x = $numAleatorio;
}

for( $i=1; $i<=$n; $i++ ) {
    generadorMultiplicativo();
    $caracter_aleatorio = $caracteres[$numAleatorio] || 'unknown';
    if($numAleatorio == 0){
        $numAleatorio++;
    }
    if($numAleatorio > 26){
        $numAleatorio = $numAleatorio - 5;
    }

    print"Letra #$i = $caracter_aleatorio\n";
}

Suggestions to improve further:

  1. Learn how to accept/return parameters from subroutines. perldoc perlsub
  2. Input validation, what if I pass in 'abc' instead of 123, numeric vs string comparison operators ( <= vs lt, == vs eq, >= vs gt, etc. ).
  3. Write comments to show high level intent of your code.
  4. Provide a usage/help message to show a new user how to use your script.
  5. The perl documentation is excellent, have a read through perldoc perlintro