相当于默认变量不起作用

İsm*_*kan 1 perl

我有一个用Perl编写的简单服务器应用程序.这是它的工作版本.

my $client;
while ($client = $local->accept() ) { 
    print "Connected: ", $client->peerhost(), ":", $client->peerport(), "\n";  

    while (<$client>) {            

        if ($mod_ctr == -1) {
            $num_count = $_;
            init();
        }
        elsif ($mod_sayaci % 2 == 0) {
            $plus_count = $_;
        }
        elsif ($mod_sayaci % 2 == 1) {
            $minus_count = $_;
            eval();
        }

        last if m/^q/gi;
        $mod_sayaci++;
    }
    print "Server awaits..\n"; 
}
Run Code Online (Sandbox Code Playgroud)

我很肯定这完美无缺.现在,当我更改我的代码以从客户端获取一个起始字符来确定操作而不是使用mod:

my $client;

while ($client = $local->accept() ) { 
    print "Connected: ", $client->peerhost(), ":", $client->peerport(), "\n";  

    $input;
    $operation;
    $value;
    while ($input = <$client>) {            

        $operation = substr($input, 0, 1);
        $value     = substr($input, 1, 1);

        print "input: $input \n";
        print "operation: $operation \n";
        print "value: $value \n";

        if ($operation == "r") {
            print "entered r \n";
            $num_count = $value;
            init();
        }
        elsif ($operation == "a") {
            print "entered a \n";
            $plus_count = $value;
        }
        elsif ($operation == "e") {
            print "entered e \n";
            $minus_count = $value;
            eval();
        }
        elsif ($operation == "q") {
            # will quit here
        }
    }
    print "Server awaits..\n"; 
}
Run Code Online (Sandbox Code Playgroud)

在客户端,我让用户以发送r为的请求开始operation.到目前为止一切正常.第一次输入后input,operationvalue打印工作正常,但它总是进入第一次if并打印entered r.我在这里错过了什么?

Bor*_*din 6

您已从使用数字更改为使用字符串来指示应执行哪些分支.您需要使用eq而不是==进行字符串比较.

像这样

if ($operation eq "r") {
    print "entered r\n";
    $num_count = $value;
    init();
}
Run Code Online (Sandbox Code Playgroud)

等等

此外,如果你补充的话,你会做自己和任何帮助你的人

use strict;
use warnings;
Run Code Online (Sandbox Code Playgroud)

到你编写的每个Perl程序的顶部.该"声明"

$input;
$operation;
$value;
Run Code Online (Sandbox Code Playgroud)

不要做任何有用的事情,除非作为评论说明在块中使用了哪些变量.写这个

my ($input, $operation, $value);
Run Code Online (Sandbox Code Playgroud)

你做了一些更有用的事情.