Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: How could I create a command line quiz?

by Fletch (Bishop)
on Mar 10, 2020 at 15:56 UTC ( #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? | Other CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2022-05-29 12:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (101 votes). Check out past polls.

    Notices?