1

I'd like to do the following in Perl:

my @triples=([3,4,5],[5,12,13],[8,5,17],[7,24,25]};

Then I want to select one of the four triples at random, then assign the elements of the selection to the variables x, y, and r.

For example, if [3,4,5] is selected at random, assign x= 3, y = 4, r =5.

Any suggestions?

2
  • 2
    my ($x, $y, $r) = @{$triplets[int(rand 4)]} like this? Commented Dec 17, 2014 at 2:42
  • Perfect answer! It works just as a needed it to work. Thanks. Commented Dec 17, 2014 at 2:55

1 Answer 1

4

An integer between 0 and 4 (4 exclusive):

int(rand 4).

Use this as the array index:

$triplets[int(rand 4)]

now dereference and assign to your variables:

my ($x, $y, $r) = @{$triplets[int(rand 4)]}

as @Jim Davids has pointed out, you can drop the int and to get a more general approach, you can use @triplets in scalar context to get the length of the array.

my ($x, $y, $r) =  @{$triplets[rand @triplets]}
Sign up to request clarification or add additional context in comments.

3 Comments

Since perl will truncate a float when specified as an array index, you don't need int. And since @arr in scalar context returns the size of the array, you could drop the hard-wired 4 and do ...= @{$triplets[rand @$triplets]}
@Jim Davids: Thanks I edited that in, but @$triplets is an array dereference of $triplets, so I replaced it with @triplets since rand enforces scalar context
Oh, right, sorry. Thought I was working with an array reference of array references for a minute there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.