17

So I have a file. Let’s say it looks like this (it's actually longer):

1234
2134
3124
4123

What is the best way to shuffle the lines in that file?

tchrist
  • 78,834
  • 30
  • 123
  • 180
Bill
  • 1,237
  • 4
  • 21
  • 44
  • what do u mean by randomly looping? – Vijay Nov 16 '12 at 12:13
  • 2
    I think he means shuffle, right Bill ? – Gilles Quénot Nov 16 '12 at 12:16
  • @sputnick Yes, That's what i mean – Bill Nov 16 '12 at 12:24
  • 3
    The Perl FAQ covers this, as well as many other common Perl questions: [How do I shuffle an array randomly?](http://perldoc.perl.org/perlfaq4.html#How-do-I-shuffle-an-array-randomly?) – Andy Lester Nov 16 '12 at 18:00
  • Besides the FAQ which @Andy kindly points out, there are [40 Perl questions that mention “shuffle”](http://stackoverflow.com/search?q=%5Bperl%5D+shuffle) that you should probably study. – tchrist Dec 06 '12 at 01:29
  • @tchrist I change the title to shuffle after I found my solution (to help others find it, on suggestion of @sputnick)... I had no idea 'shuffle' existed. I had something like "What's the best way to randomize an array". Are you just pointing out that there are lots of questions about shuffle or do you really think I need to read those other questions? – Bill Dec 06 '12 at 12:11

1 Answers1

34
#!/usr/bin/env perl

use strict;
use warnings;

use List::Util qw/shuffle/;

my @arr = shuffle <>;

print @arr;

Usage :

./script file.txt
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223