Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

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

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 exercise, from my lab. I can't find a way to do solve this, because I am new in Perl.

In C, generating this array would by very easy, but I don't know how to do it in Perl.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For amusement value:

A method that works on systems where EOL is a single character:

#!/usr/bin/perl

use strict;
use warnings;

$/ = 1;

open 0;
my @r = map rand,<0>;

print "@r
";

A possibly nondeterministic method that does not use for, while, until:

#!/usr/bin/perl
use strict; use warnings;

my @rand;

NOTLOOP:
push @rand, rand;
sleep 1;
goto NOTLOOP if 100 > time - $^T;

print 0 + @rand, "
";

Using regular expressions:

#!/usr/bin/perl
use strict; use warnings;

my $s = '-' x 100;
$s =~ s/(-)/rand() . $1/eg;
my @rand = $s=~ m/([^-]+)/g;

Copying and pasting 100 rand invocations by hand is really passé:

#!/usr/bin/perl
use strict; use warnings;

my $s = '(' . 'rand,' x 100 . ')';
my @rand = eval $s;

A file I/O based solution that does not require /dev/random:

#!/usr/bin/perl
use strict; use warnings;

$/ = 1;

my @rand;

seek *DATA, 0, 0;

NOTLOOP:
scalar <DATA>;
push @rand, rand;
goto NOTLOOP if $. < 100;
__DATA__

No reason to use recursion with Perl's goto

#!/usr/bin/perl
use strict; use warnings;
use autodie;

$/ = 1;

open my $F, '<', ( 1 x 100 . 0 );

my @rand or &notloop;

sub notloop {
    my $t = <$F>;
    $t or return;
    push @rand, rand;
    goto &notloop;
}

Here is a recursive string eval version:

#!/usr/bin/perl
use strict; use warnings; use autodie;

local $/ = 1;
open my $F, '<', ( 1 x 100 . 0 );

my @rand;

eval <<'NOLOOP'
my $self = (caller(0))[6];
<$F> or die;
push @rand, rand;
eval $self;
NOLOOP
;

Of course, all of these actually do contain loops, but they do not use the keywords you were barred from using.

NB: This question has brought out the wacko in me, but I must admit it is amusing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...