in reply to Reading a File by Line then Analyzing each Line

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"; }