有人知道为什么会这样吗?
$ perl -e '@arr = []; print "HELLO." unless grep {/asdf/ =~ $_} @arr;'
Run Code Online (Sandbox Code Playgroud)
输出:
HELLO.
Run Code Online (Sandbox Code Playgroud)
但
$ perl -e '@arr = undef; print "HELLO." unless grep {/asdf/ =~ $_} @arr;'
Run Code Online (Sandbox Code Playgroud)
没有输出.
对我来说,似乎两者都应输出"你好".
您的代码中存在一些语法错误,这些错误会导致意外结果.
首先,如果你想要一个空数组,你需要写:
# Correct (creates an empty array)
my @array = ();
# Incorrect (creates a one-element array containing a reference to an empty array)
my @array = [];
# Incorrect (creates a one-element array containing the undef element)
my @array = undef;
Run Code Online (Sandbox Code Playgroud)
您还需要反转grep条件 - 正则表达式应位于=~运算符的右侧:
perl -e '@arr = (); print "HELLO." unless grep { $_ =~ /asdf/} @arr;'
Run Code Online (Sandbox Code Playgroud)
如果您进行了这两项更改,代码将按预期执行.