2012-10-25 23 views
-3

我目前正在嘗試提取並分解包含溫度讀數的網頁的信息。當談到Perl時,我是一個完整的初學者,我遇到了一些麻煩。我試圖從中提取信息的頁面是:http://temptrax.itworks.com/temp。 到目前爲止,我能夠弄清楚如何獲取頁面並使用拆分將四個溫度讀數分成四行。以下是我能想出這麼遠:使用case語句使用Perl從網頁檢索信息

#!/usr/bin/perl 
use warnings; 
use LWP::Simple; 
use v5.10.1; 

my $content = get('http://temptrax.itworks.com/temp'); 
my @split = split ('Probe',$content); 

foreach my $split(@split){ 
$split =~ s/'Probe''|'/ /g; 

print $split . "\n"; 

} 

是我在與被分離使用的情況下報告的四個溫度讀數麻煩下一步。我不太明白如何去做。當給出特定數字1-4時,我希望能夠分別爲每個探針讀取讀數。什麼是最好的方法來做到這一點?

+0

什麼叫'case'語句是什麼意思? –

+0

你的問題是什麼? –

+0

我可能以錯誤的方式回答了這個問題。抱歉。我想要做的是這樣的:switch($ temp){ case「1」{print「temperature for probe 1」} – MD87

回答

0

通過直接解析爲一個散列,我們可以簡單地遍歷這些鍵,或者做任何其他人想要處理的數據結構。沒有case需要。 BTW Switch模塊已被棄用,並且確實不應該使用。

#!/usr/bin/env perl 

use strict; 
use warnings; 

use LWP::Simple; 

my $content = get('http://temptrax.itworks.com/temp'); 
my %probes = $content =~ /Probe\s*(\d)\|\s*(\-?[\d\.]+)/g; 

foreach my $probe (sort keys %probes) { 
    print "$probe => $probes{$probe}\n"; 
} 

正則表達式可以通過這個來解釋(甚至替換):

my %probes = $content =~/
    Probe\s*  # starts with Probe 
    (   # start capture 
    \d   # a number (probe) 
)    # end capture 
    \|\s*   # separated with a pipe symbol 
    (   # start capture 
    \-?   # possibly negative 
    [\d\.]+  # digits or decimals (at least one) 
)    # end capture 
/gx; 
+0

太棒了!非常感謝你的深入解釋。 – MD87