Personally, I'd read everything into a hash.

use Data::Dumper; my (%quiz, $number); while (<DATA>){ chomp; if (s/^(\d+)\. *//) { $number = $1; $quiz{$number}{question} = $_; } elsif (s/^([A-Z])\. *//) { my $option = $1; $quiz{$number}{answer} = $option if s/ *\*$//; $quiz{$number}{$option} = $_; } else { next; } } print Dumper \%quiz; __DATA__ 1. What is my name? A. Rooney * B. Gerrard C. Ronaldo D. Ronaldinho 2. Who's your bet in the coming World Cup? A. Brazil * B. Germany C. England D. Cameroon

You can then do things like: "What is the answer to question two?"

print $quiz{2}{$quiz{2}{answer}};

or, "Display question 1:"

print '1. ',$quiz{1}{question},"\n"; for ( sort keys %{$quiz{1}} ){ print "$_. ",$quiz{1}{$_},"\n" if $_ !~ /\p{Lower}/; }

or, "Display them all:"

for (sort keys %quiz) { my $number = $_; print "\n$number. $quiz{$number}{question}\n\n"; for ( sort keys %{$quiz{$number}} ){ next if /question|answer/; print "$_. $quiz{$number}{$_}\n"; } print "\nAnswer: $quiz{$number}{answer}\n"; }

Update: or a little clearer:

for (sort keys %quiz) { my $current = $quiz{$_}; print "\n$_. $current->{question}\n\n"; for ( sort keys %{$current} ){ next if /question|answer/; print "$_. $current->{$_}\n"; } print "\nAnswer: $current->{answer}. $current->{$current->{answer} +}\n"; }

In reply to Re: Reading a File by Line then Analyzing each Line by thundergnat
in thread Reading a File by Line then Analyzing each Line by soon_j

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.