tags:

views:

139

answers:

2

Hello,

I'm already developing that project to my family, but now i'm needing to link a Name to another aleatory(remember that the first name i have it) and store only the second name in a variable, remember that this list is a file(*.txt) with some names, but how i can do this? Thanks.

+2  A: 

The English in your question is so bad that I'm having a really hard time understanding what you are asking.

But what about this?

use List::Util qw(shuffle);
my @array = shuffle(<>);
print shift @array;

That reads from STDIN, you can always use open to open a file then use on your file handle.

Here it is with file IO:

use List::Util qw(shuffle);
open my $fh, "<", "out.txt";
my @array = shuffle(<$fh>);
print shift @array;
close $fh;
tster
Thanks, i'm going to try this and very sorry about my english :(
Nathan Campos
@Nathan thanks for my "word of the day": http://en.wikipedia.org/wiki/Aleatoricism
martin clayton
When i try to do this i'm getting this error: `"suffle" is not exported by the List::Util module`
Nathan Campos
Looks like a typo? Should be "shuffle".
martin clayton
This is pretty wasteful of compute time and the random number generator's entropy. If you want a random stream, shuffle the list. If you just want one random element of the array, just ask for that.
jrockway
+6  A: 

Okay, you seem to want to get a random name from a file. Assuming these names are on separate lines, here's what you can do (please read about the built-in rand, int and chomp methods in perldoc perlfunc to see how they work):

my @names = <>;
chomp(@names);
my $random_name = $names[int(rand(@names))];

Breaking this down into steps, this is what it does:

  • first, we read in the file. If you pipe the file into your script (like perl myscript.pl < names.txt), you can read directly from STDIN, with <>.
  • then, we remove all the newlines from each line with chomp.
  • now we want to get a random element from the list:
  • @list in scalar context get the number of elements in the list (for example, 4)
  • rand(4): get a random number between 0 and 4 (so we could have a number between 0 and 3.999999...)
  • int(some number from above) that was a floating-point number, so let's round it down (so now we have either 0, 1, 2, or 3: which is exactly the possible array indexes for our list!
  • use that as the array index into @list and we're done!
Ether
It's even easier in Perl6 `my $value = @list.pick`
Brad Gilbert
And even overly complex for Perl5: `$names[rand @names]` will do just fine.
Randal Schwartz
yeah I totally didn't intuit that an integer would be coerced from a floating point value for an array index, but after all, Perl DWIM :)
Ether
@Ether: welcome to "integer context" :) (Array or list-slice indicies, operands of .. where the other operand is numeric, substr 2nd and 3rd operands, etc.)
ysth