Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: What can I be doing wrong with this array in this particular section?

by Athanasius (Chancellor)
on Jan 13, 2018 at 07:31 UTC ( #1207185=note: print w/replies, xml ) Need Help??

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 ["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:

  • Always begin each script with use strict; and use warnings;
  • The line $answer = substr($line,0); does nothing
  • When opening a file, prefer the 3-argument form: open(my $file, '<', 'quiz4.txt');
  • Always check the result of an open or close operation: either use autodie;, or test explicitly:
    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";
  • Trim newline characters from lines using chomp or via a regular expression (see below).

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


17:26 >perl { 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,

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2018-08-17 23:11 GMT
Find Nodes?
    Voting Booth?
    Asked to put a square peg in a round hole, I would:

    Results (184 votes). Check out past polls.