2011-10-11 62 views
0

嗨我正在研究一個小的解析腳本,最好在Perl中解析一組給定的問題。總是有四個問題(目前用於測試目的)。他們的格式如下:如何解析隨機選擇的一組給定問題?

Junk 
Junk 
Junk 
(1) 

How is the weather in India? 
A Good 
B Bad 
C Terrible 
(2) 

Are you hungry right this second? 
True 
False 
(3) 

Which is a fruit? 
A Africa 
B China 
C India 
D Asia 
E America 
F Apple 
G Mexico 
(4) 

A mystery is? 
A Game 
B Problem 
C I don't know 
D Nothing

所以模式是相同的,數字(1)先來,然後是一個空白後跟問題。現在答案可以選擇可以改變,我試圖找出一種方法來保持它的一致性。我已經想出了一種方法去除所有問題並將它們放入哈希中。現在我需要存儲與他們相對應的選擇。

我的代碼現在可以去除上面的內容到具有如下內容的數組:

PRINTING ARRAY OF Q'S 
How is the weather in India? 
Are you hungry right this second? 
Which is a fruit? 
A mystery is? 

代碼是:

#! /usr/bin/perl 
use strict; 
use warnings; 

open (FILE, "$ARGV[0]"); 



my @questions =(); 

my $flagToCapture = 0 ; 
my $foundQuestion = 0 ; 

while (<FILE>){ 

if ($flagToCapture ==2) { 
    $flagToCapture = 0; 
    chomp($_); 
    push(@questions, $_); 
    #inserted question into the array 
    $foundQuestion = 1; 
} 

if ($flagToCapture == 1){ 
    $flagToCapture = 2; 
} 

if ($_ =~ m/^\(/) { 
    $flagToCapture =1; 
} 

} 

print "PRINTING ARRAY OF Q'S \n"; 
foreach(@questions){ 
    print "$_\n"; 
} 

回答

1

我會做這樣的事情:

#!/usr/bin/perl 
use strict; 
use warnings; 
use Data::Dump qw(dump); 

my $quest; 
my %QA; 
while(my $line = <DATA>) { 
    chomp $line; 
    if ($line =~ /^\((\d+)\)$/) { 
     $quest = $1; 
     $QA{$quest} = []; 
    } elsif ($line =~ /\S+/ && defined $quest) { 
     push @{$QA{$quest}}, $line; 
    } 
} 
dump %QA; 

__DATA__ 
Junk 
Junk 
Junk 
(1) 

How is the weather in India? 
A Good 
B Bad 
C Terrible 
(2) 

Are you hungry right this second? 
True 
False 
(3) 

Which is a fruit? 
A Africa 
B China 
C India 
D Asia 
E America 
F Apple 
G Mexico 
(4) 

A mystery is? 
A Game 
B Problem 
C I don't know 
D Nothing 

輸出:

(
    4, 
    [ 
    "A mystery is?", 
    "A Game", 
    "B Problem", 
    "C I don't know", 
    "D Nothing", 
    ], 
    1, 
    ["How is the weather in India?", "A Good", "B Bad", "C Terrible"], 
    3, 
    [ 
    "Which is a fruit?", 
    "A Africa", 
    "B China", 
    "C India", 
    "D Asia ", 
    "E America", 
    "F Apple", 
    "G Mexico", 
    ], 
    2, 
    ["Are you hungry right this second?", "True", "False"], 
) 
0

我想出了一個辦法來去除所有的問題並將它們放入哈希中。現在我需要存儲與他們相對應的選擇。

大,得到的答覆是,下面的問題線條的答案,所以一旦你發現一個問題,只是繼續追加你看行,直到你達到1),一個新的問題或2)空行

更新:如果你不打算做錯誤檢查自己,use autodie; 簡單的版本,發現的問題編號,其他一切被認爲是內容

use autodie; 
... 
my %questions; 
my $questionNumber = ''; 
while (<FILE>){ 
    if(/^\s* \((\d+) \) \s* $/x){ 
     $questionNumber = $1; 
     $questions{ $questionNumber } = ''; 
    } else { 
     $questions{ $questionNumber } .= $_; 
    } 
} 
while(my($k, $v) = each %questions){ 
    print "($k)$v\n"; 
    print Dumper($k => QuestionToHash($v)); 
} 
+0

這可能是一個愚蠢的問題,因爲它是在深夜......我怎麼繼續增加,直到我到達下一個(#)?我會在頂部添加一些代碼。 – user791953