in reply to Extract random records from text file

This works for me:
local $,=$/."****".$/; local $\=$/; sub rand_questions { my $total=shift; local $/ = "===\n"; # set our delimiter my @data=<DATA>; #fisher yates shuffle my $i; for ($i = @data; --$i; ) { my $j = int rand ($i+1); # next if $i == $j; # See tillys reply @data[$i,$j] = @data[$j,$i]; } my @questions=@data[0..$total-1]; return @questions; } print rand_questions(2); __DATA__ question=When driving towards a bright setting sun, glare can be reduc +ed by option1=closing one eye option2=dipping in the interior mirror option3=wearing dark glasses option4=looking sideways answer=4 answertext=Dark glasses are often used as a fashion item but they do h +ave their practical uses. Low sun in the early morning or evening can + dazzle and distract. Lessen the risk by reducing the glare. Wear dar +k glasses if they help you to see better. category1=car category2=vechicle handling === question=2When driving towards a bright setting sun, glare can be redu +ced by option1=closing one eye option2=dipping in the interior mirror option3=wearing dark glasses option4=looking sideways answer=4 answertext=Dark glasses are often used as a fashion item but they do h +ave their practical uses. Low sun in the early morning or evening can + dazzle and distract. Lessen the risk by reducing the glare. Wear dar +k glasses if they help you to see better. category1=car category2=vechicle handling === question=3When driving towards a bright setting sun, glare can be redu +ced by option1=closing one eye option2=dipping in the interior mirror option3=wearing dark glasses option4=looking sideways answer=4 answertext=Dark glasses are often used as a fashion item but they do h +ave their practical uses. Low sun in the early morning or evening can + dazzle and distract. Lessen the risk by reducing the glare. Wear dar +k glasses if they help you to see better. category1=car category2=vechicle handling ===
HTH Update I left out various errorchecking and the like, but you can add that.

Yves
--
You are not ready to use symrefs unless you already know why they are bad. -- tadmc (CLPM)

Replies are listed 'Best First'.
Re (tilly) 2 (small optimization): Extract random records from text file
by tilly (Archbishop) on Oct 02, 2001 at 22:26 UTC
    As noted in Fisher-Yates Shuffle, the check for whether the two elements are equal is inefficient. The cost of adding the check scales linearly with the number of elements. The number of saved swaps scales logarithmically.

    The only time it is important to have the check is when your swap will run into trouble if the two elements are the same. This is true in C if you are using xor to perform the swap in place. It is not true in Perl. Therefore in Perl it is both faster and clearer to drop the check.