1

我对 Perl 很陌生。我的 Perl 程序正在从浏览器获取 HTTP 请求消息,我想检测最后一个空行。

我试图使用$_ =~ /\S/,但它不起作用:

while (<CONNECTION>) {
  print $_;
  if ($_ =~ /\S/) {print "blank line detected\n"; }
}

输出是

GET / HTTP/1.1
blank line detected
Host: xxx.ca:15000
blank line detected
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:5.0) Gecko/20100101 Firefox/5.0
blank line detected
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
blank line detected
Accept-Language: en-us,en;q=0.7,zh-cn;q=0.3
blank line detected
Accept-Encoding: gzip, deflate
blank line detected
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
blank line detected
Connection: keep-alive
blank line detected
Cookie: __utma=32770362.1159201788.1291912625.1308033463.1309142872.11; __utmz=32770362.1307124126.7.3.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=Manitoba%20Locum%20Tenens%20Program; __utma=70597634.1054437369.1308785920.1308785920.1308785920.1; __utmz=70597634.1308785920.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=leung%20carson
blank line detected



我试图使用 chomp(),这对我也不起作用:

  while (<CONNECTION>) {
    chomp(); 
    print "$_\n";
    if ($_ eq "") {print "blank line detected\n"; }
  }

输出:

GET / HTTP/1.1
Host: xxx.ca:15000
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:5.0) Gecko/20100101 Firefox/5.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.7,zh-cn;q=0.3
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: keep-alive
Cookie: __utma=32770362.1159201788.1291912625.1308033463.1309142872.11; __utmz=32770362.1307124126.7.3.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=Manitoba%20Locum%20Tenens%20Program; __utma=70597634.1054437369.1308785920.1308785920.1308785920.1; __utmz=70597634.1308785920.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=leung%20carson

先谢谢了~

4

2 回答 2

3

要检测只有空白的行,

while (<CONNECTION>) {
  print $_;
  if ($_ =~ /\S/) {print "blank line detected\n"; }
}

应该

while (<CONNECTION>) {
   print $_;
   if ($_ !~ /\S/) {print "blank line detected\n"; }
}

或者简称,

while (<CONNECTION>) {
   print;
   if (!/\S/) {print "blank line detected\n"; }
}

原因

while (<CONNECTION>) {
   chomp(); 
   print "$_\n";
   if ($_ eq "") {print "blank line detected\n"; }
 }

可能不起作用是因为 HTTP 标头行以 \r\n 结尾。你需要

while (<CONNECTION>) {
   s/\r?\n//; 
   print "$_\n";
   if ($_ eq "") {print "blank line detected\n"; }
 }
于 2011-06-30T20:45:26.633 回答
1

我想你想要:

/^\s+$/

用于空行检测。

使用 /\S/ 将检测非空行。

更好的是,使用 Net::HTTP 或 LWP 之类的东西为您完成繁重的工作。一些 HTTP 编码问题是微妙的。

于 2011-06-30T20:44:23.630 回答