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
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";