如何使用Perl比较两个字符串

时间:2017-04-18 22:43:43

标签: perl

我用谷歌搜索,直到我用完选项。我一定做错了什么,但我无法弄清楚是什么。 (显然我是Perl的新手并继承了这个项目)。 我只是想看看变量是否等于' Y'。正如您可以在下面的代码底部看到的那样,我已经尝试过' eq',' ='和' =='。除了设置一个等于“eq”的结果的新变量之外。操作,所有尝试都会导致页面爆炸。字符串测试($ stringtest)的结果似乎是空的,如果不是,我就不知道如何测试它。

#!/usr/bin/perl -w
#######################################################################
# Test script to show how we can pass in the needed information
# to a web page and use it to run a program on the webserver and
# redirect its output to a text file.
#######################################################################
require 5;  #Perl 5 or greater
require "jwshttputil.pl";
require "jwsdbutil.pl";

# Parse QUERY_STRING
&HTTPGet;
# Parse POST_STRING - NOTE: This CLEARS the post data
&HTTPPost;

print STDOUT "Content-type: text/html\n\n";
print STDOUT "<HTML><BODY>";

$canrun = "Y";
$is4ge = $Data{'is4ge'};
$sYes = "Y";

#Step 1: Check for needed values
if ( !($Data{'user'}) )
{
    print "user was not found<br/>";
    $canrun = "N";
}
if ( !($Data{'pwd'}) )
{
    print "pwd was not found<br/>";
    $canrun = "N";
}
if ( !($Data{'is4ge'}) )
{
    print "is4ge was not found<br/>";
    $canrun = "N";
}
print "$Data{'is4ge'}";         #prints Y
print $is4ge;                   #prints Y
if ( !($Data{'db'}) )
{
    print "db was not found<br/>";
    #if (!($is4ge = "Y"))       #dies
    #    $canrun = "N";

    #if (!($is4ge eq "Y"))  #dies
    #    $canrun = "N";

    #$stringtest = ($is4ge eq $sYes);
    #print $stringtest;     #displays nothing

    #if (($is4ge == $sYes)) #dies
    #    $canrun = "N";
}

print STDOUT "</BODY></HTML>";

2 个答案:

答案 0 :(得分:6)

在Perl中,流控制语句体周围的曲线不是可选的。

eq确实是Perl中的字符串比较运算符。

所以,

if (!($is4ge eq "Y")) {
    $canrun = "N";
}

或者只是

if ($is4ge ne "Y") {
    $canrun = "N";
}

您确实应该使用10代替'Y''N',因为它们是真的,而且可以更容易地测试错误值。

答案 1 :(得分:5)

您对自己的问题有一个很好的答案,但指出您自己如何对此进行调查可能会有所帮助。

首先,这个问题的原始标题是&#34;如何比较Apache下的CGI页面中的两个字符串?&#34;该标题已被更正,因为此问题与CGI或Apache无关,它只是对Perl语法的误解。我知道你最初不可能知道这一点,但调查这样的奇怪错误的一个好方法是尽可能消除许多并发症。所以忘记CGI和Web服务器 - 只需编写一个简单的Perl程序。

#!/usr/bin/perl

$canrun = 'N';
$is4ge  = 'Y';

if (!$is4ge eq 'Y')
  $canrun = 'Y';

print $canrun;

运行这个,我们得到:

$ perl testif
Scalar found where operator expected at testif line 7, near ")
  $canrun"
    (Missing operator before $canrun?)
syntax error at testif line 7, near ")
  $canrun "
Execution of testif aborted due to compilation errors.

这清楚表明问题是第6行和第7行的语法。这可能足以让你发送到Perl syntax manual page,在那里你会发现Perl中的条件语句总是需要在块周围使用大括号。如果没有,您可以添加diagnostics编译指示以获取更多信息。

因为您已经被告知,正确的测试格式是

if ($is4ge ne 'Y') {
   $canrun = 'Y';
}

但是这个程序中还有一些其他东西将来很难维护。基本上,它倾向于落后于Perl最佳实践。

  • 在Perl 5.6.0(2000年发布)中用-w替换后,您使用use warnings
  • 您在代码中没有use strict(这会在您的代码中指出您想要解决的许多不良做法 - 特别是,您需要声明你的变量)。
  • 程序顶部的require d两个库可能会被更好地重写为正确的Perl模块。
  • 我担心jwshttpdutil.pl可能是一个自制的CGI解析器,应该用CGI.pm替换。
  • 代码中嵌入的HTML应该替换为某种模板引擎。

另外,我建议您阅读CGI::Alternatives以了解最新的现代Perl方法来编写Web应用程序。你正在使用在上一个千年结束之前已经过时的技术。