Quoth Roger <>:
>
> My code is this:
>
> use warnings;
> use strict;
>
> my $number = my_rand();
> print "The number is ".$number;
> { my $seed = 1;
Why the bizzare indentation?
> sub my_rand (){
>
> $seed = int(($seed * 1103515245 + 12345) / 65536) % 32768;
> return $seed;
> }
You have a missing } here.
> I derived it from an article here: (apparently wrong??)
> http://perl.plover.com/FAQs/Namespac...xical_variable
No, this is a good basic description of how my and local work. The
problem is elsewhere.
> The issue is that declaring 'seed' inside the brackets as shown above yields
> an error of:
> main::my_rand() called too early to check prototype at test_scope.pl line 6.
> Use of uninitialized value in multiplication (*) at test_scope.pl line 11.
The problem is with these:
sub my_rand () {
^^
They are called a prototype, for which see perldoc perlsub. It will
suffice to say now that 1. they are an advanced feature of Perl and you
don't need to use them and 2. that perl needs to know a sub's prototype
*before* it encounters any calls to that sub (as the warning said).
The other warning comes from the fact that the assignment $seed = 1 is
not executed until after the call to my_rand. There are two fixes for
this: either move the whole block up above any calls to the sub, so that
the variable is initialised properly, or, better, make it into a BEGIN
block that will *definitely* be run before anything else. For BEGIN
blocks c.f. perldoc perlmod.
So, to fix your code you want
use warnings;
use strict;
# if you put
# use subs qw/my_rand/;
# here, you can call my_rand without parens
my $number = my_rand();
print "The number is $number\n";
BEGIN {
my $seed = 1;
sub my_rand { # Note: no ()
$seed = int (...);
return $seed;
}
}
Ben
--
Musica Dei donum optimi, trahit homines, trahit deos. |
Musica truces molit animos, tristesque mentes erigit. |
Musica vel ipsas arbores et horridas movet feras. |