Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a script that uses "rand" to add one of the four letters (ATCG) to a string:

#!/bin/perl use warnings; use strict; my $i =0; my $x; my $aa = ""; for ($i;$i<5007;$i++){ $x = int(rand(4)); if ($x == 0) { $aa .= 'A'; } elsif ($ x== 1) { $aa .= 'T'; } elsif ($x == 2) { $aa .= 'C'; } else { $aa .= 'G'; } } open (FILE, '>./test'); print FILE "$aa"; close (FILE);

It works but also sends : "Useless use of private variable in void context at 8 line 24." What does it mean?

Replies are listed 'Best First'.
Re: Useless use of private variable in void context at
by GrandFather (Saint) on Nov 23, 2014 at 22:13 UTC

    You are using a C style for loop. The first element of the for loop header is an initialization statement, but $i doesn't actually do anything - it is a variable used in a silly place (void context) because the value isn't used there.

    But, you'd be much better to use a Perl loop:

    for my $i (0 .. 5006) { ... }

    which makes what is going on much clearer. But for your particular problem you could:

    #!/bin/perl use strict; use warnings; my $thing = join '', map{qw(a t c g)[rand 4]} 1 .. 5007; my $fName = "./test"; open my $outFile, '>', $fName or die "Can't create '$fName': $!\n"; print $outFile $thing; close $outFile;

    Note the three parameter open, lexical file handle and a check that the open succeeded.

    Perl is the programming world's equivalent of English

      Thanks!

      Note that for (;$i<5007;$i++) is also valid.

      Update:

      While this is considered "very un-Perl-ish", it is very common in C/C++ and even C# (though both C++ and C# also have for-each syntax, as well). Therefore, there are many developers who are more comfortable with this form.

        Also needlessly obscure and error prone compared to a Perl loop (for (1 .. 5007) {...}) used for performing some number of iterations of a loop.

        Perl is the programming world's equivalent of English
Re: Useless use of private variable in void context at
by roboticus (Chancellor) on Nov 23, 2014 at 23:14 UTC

    Ignore me, I missed the "rand" statement....

    Grampa already gave you a good answer, so I won't belabor that. I wanted to mention, though, that you can build your string even more simply using the "x" operator:

    my $aa = 'A' . 'T' . 'C' . 'G'x5003;

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.