#!/usr/bin/perl -w
#Serge Sharoff, University of Leeds
#Filters N randomly chosen lines from STDIN
use strict;
undef my %randomlist;
my $count=0;
my $n=shift;
die "Usage: $0 N\nfor getting N random lines from a list" unless $n;# and ($n=~/\D/);
my @lines=<>;
my $total=scalar(@lines);
if ($total<=$n) {
    print STDERR "The number of lines $total is less than the output length $n\nCopying the input to output\n";
    print "@lines";
} else {
    while ($count<$n) { # initialise the random list
	my $newrandom=int(rand($total-1));
	unless (exists $randomlist{$newrandom}) {
	    $randomlist{$newrandom}=1;
	    $count++;
	}
    };
    foreach (sort {$a <=> $b} keys %randomlist) {
	print $lines[$_];
    }
};
