Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 带有或的正则表达式。我做错了什么?_Regex_Perl - Fatal编程技术网

Regex 带有或的正则表达式。我做错了什么?

Regex 带有或的正则表达式。我做错了什么?,regex,perl,Regex,Perl,我有这个脚本,出于某种原因总是返回-1 #!/usr/bin/perl use strict; use warnings; use Test::More tests => 4; is(scrub(''), '-1'); is(scrub('~'), '-1'); is(scrub('undef'), '-1'); is(scrub('a'), 'a'); sub scrub { my $a = shift; if ($a =~ m/~|undef|/) {

我有这个脚本,出于某种原因总是返回
-1

#!/usr/bin/perl

use strict;
use warnings;

use Test::More tests => 4;

is(scrub(''), '-1');
is(scrub('~'), '-1');
is(scrub('undef'), '-1');
is(scrub('a'), 'a');

sub scrub {
    my $a = shift;

    if ($a =~ m/~|undef|/) {
        return -1;
    }

    return $a;
}
我想要的是,当
~
或perl的
未定义
或空字符串``作为参数时,它只返回
-1

有人知道怎么了吗

更新:根据回复,这是正确的方法

sub scrub {
    my $a = shift;

    return ($a =~ m/^(~|undef|^$)$/) ? -1 : $a;
}

正则表达式不是此作业的合适工具。使用eq运算符测试字符串相等性,使用defined()运算符测试undef

if ($a eq '' or $a eq '~' or not defined $a) {
    return -1;
}

顺便说一句,这里有第四个$a值将返回-1,即$a已经是-1。

/undef/检查字符串“u”、“n”、“d”、“e”、“f”,而不是未定义的值。测试应为
is(脚本(未定义),-1)