perlrandomperl-modulesrand

Call srand only once when loading perl modules


My script is separated into multiple packages. main.pl loads A.pm, which loads A::B.pm and A::C.pm. They all use rand. However, if I specify a seed for srand in main.pl, the latter modules seem to generate their own seed anyway. How can I seed the RNG only once and have the entire script predictable?


Solution

  • Put srand in a BEGIN block in main.pl, before loading A:

    use strict;
    use warnings;
    ...
    
    BEGIN { srand(7) }
    use A;
    ...
    

    A complete example:

    A.pm:

    package A;
    
    use B;
    use C;
    
    CORE::say "A: ", rand();
    

    B.pm:

    package B;
    
    CORE::say "B: ", rand();
    

    C.pm:

    package C;
    
    CORE::say "C: ", rand();
    

    main.pl:

    BEGIN { srand(7) }
    
    use A;
    
    CORE::say "main: ", rand();
    

    Running perl -I . main.pl always print:

    B: 0.266444196765409
    C: 0.682035230190621
    A: 0.265490593427
    main: 0.129110848853948
    

    If I put srand(7) after use A, then the first three prints (from A, B and C) are randoms, and only the one in main.pl is always the same.