in reply to What can I be doing wrong with this array in this particular section?
Hello tjox, and welcome to the Monastery!
You say “my problem appears to be generating the answer key from the file”, but you don’t say why that is. As far as I can see, the code you’ve shown is doing the job. Here is what I get (using Data::Dump to show the contents of @answers):
17:17 >perl 1859_SoPW.pl ["a. answer \n", "b. answer \n", "c. answer \n"] 17:18 >
That said, there are a number of ways in which the code could be improved:
my $file = 'quiz4.txt'; ... open(my $fh, '<', $file) or die "Cannot open file '$file' for reading, stopped"; ... close $fh or die "Cannot close file '$file', stopped";
In addition, I would read and store question numbers as well as the answers; and I would separate the letter code of the correct answer from the description that follows, thereby making it easier to test whether a given answer is correct:
use strict; use warnings; use Data::Dump; my %answers; my $question; while (my $line = <DATA>) { if ($line =~ / ^ (\d+) \. /x) { $question = $1; } elsif ($line =~ / ^ \* (\w+) \. \s* (.*?) \s* $ /x) { warn "Overwriting answer for question $question" if exists $answers{$question}; $answers{$question} = [$1, $2]; } } dd \%answers; __DATA__ 1. question? *a. answer begin end b. answer c. answer 2. question? a. answer *b. answer c. answer 3. question? a. answer b. answer *c. answer
Output:
17:26 >perl 1859_SoPW.pl { 1 => ["a", "answer begin end"], 2 => ["b", "answer"], 3 => ["c", "answer"], } 17:27 >
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|