user2054454
user2054454

Reputation: 21

What does this piece of Perl code do in laymans terms?

Found this inside a loop. I've read up about splice but it just confused me more. I'm not familiar with Perl, but am trying to translate an algorithm to another language.

my $sill = splice(@list,int(rand(@list)),1);
       last unless ($sill);

To be more specific: What will be inside $sill if it doesn't exit the loop from the last?

Thanks for any help!

Upvotes: 2

Views: 84

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 185106

That means :

  • remove a random element from the array list (0 -> numbers of element of the list) and
  • assign the sill variable with the removed element (pop() like) and
  • exit the loop if sill variable is false

See http://perldoc.perl.org/functions/splice.html

Upvotes: 2

amon
amon

Reputation: 57600

This randomly removes one element from the array @list. That value is assigned to $sill. If that was a false value, the enclosing loop (not shown) is broken out of.

splice takes an array, an offset, and a length, plus a replacement list. If the replacement is omitted, the elements are deleted.

The length is constant (1 element), but the offset is calculated as a random integer smaller between 0 and the length of @list.

Upvotes: 4

Related Questions