How to generate an array with random values, without using a loop?

后端 未结 24 2118
逝去的感伤
逝去的感伤 2020-12-13 19:23

How can I generate an array in Perl with 100 random values, without using a loop?

I have to avoid all kind of loops, like \"for\", foreach\", while. This is my exerc

24条回答
  •  粉色の甜心
    2020-12-13 19:54

    Using an anonymous sub and recursion:

    use strict;
    use warnings;
    
    my @foo;
    my $random;
    ($random = sub {
            push @{$_[0]}, rand;
            return if @{$_[0]} == $_[1];
            goto \&$random;
    })->(\@foo, 100);
    
    print "@foo\n";
    print scalar @foo, "\n";
    

    Using computed goto, for all the fortran fans:

    use strict;
    use warnings;
    
    sub randoms {
            my $num = shift;
            my $foo;
            CARRYON:
                    push @$foo, rand;
                    # goto $#{$foo} < 99 ? 'CARRYON' : 'STOP';
                    goto ( ('CARRYON') x 99, 'STOP' )[$#$foo];
            STOP:
                    return @$foo;
    }
    
    my @foo = randoms(100);
    print "@foo\n";
    print scalar(@foo)."\n";
    

    2 anonymous subs and an arrayref:

    use strict;
    use warnings;
    
    my @bar = sub {  return &{$_[0]} }->
    (
            sub {
                    push @{$_[1]}, rand;
                    goto \&{$_[0]}
                            unless scalar(@{$_[1]}) == $_[2];
                    return @{$_[1]};
            },
            [],
            100
    );
    
    print "@bar\n";
    print scalar(@bar), "\n";
    

提交回复
热议问题