Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: How could I create a command line quiz?

by Fletch (Bishop)
on Mar 10, 2020 at 15:56 UTC ( [id://11114081]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11114081]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (6)
As of 2024-04-18 20:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found