http://qs1969.pair.com?node_id=11114081


in reply to How could I create a command line quiz?

Shelling out to cat or grep in backticks is almost never what you want to do (unless you're doing a one-liner throwaway or something). And your approach loses the correspondence between questions and answers.

You should write a sub, let's call it parse_quiz_text, which will take the filename and return your questions and answers. The sub can cheat and use local $/ = q{}; (see perlvar) to say you want to read in paragraph mode, then you'd split off the first line from the answer(s). Each question would be represented by a hashref of the question and an arrayref of answers (perldsc and perlref will be useful if you're unfamiliar with those).

sub parse_quiz_text { my( $quiz_file ) = @_; open( my $fh, q{<}, $quiz_file ) or die "problem opening quiz '$quiz +_file': $!\n"; local( $/ ) = q{}; my @quiz_questions; while( defined( my $paragraph = <$fh> ) ) { my @lines = split( /\n/, $paragraph ); push @quiz_questions, { question => (shift @lines), answers => \@l +ines }; } close( $fh ); return @quiz_questions; }

Additionally: caveat that this does no error checking and is presuming the file is in the correct format (e.g. questions are always the first line of a paragraph, questions are always followed by at least one answer, yadda yadda yadda). You'd probably want to add some error checking at some point (check that the first line of the paragraph ends in a '?', check that @lines >= 2, . . .).

The cake is a lie.
The cake is a lie.
The cake is a lie.