string 在 Perl 中检查字符串是否为空的正确方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2045644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the proper way to check if a string is empty in Perl?
提问by Nick Bolton
I've just been using this code to check if a string is empty:
我一直在使用此代码来检查字符串是否为空:
if ($str == "")
{
// ...
}
And also the same with the not equals operator...
与不等于运算符相同...
if ($str != "")
{
// ...
}
This seems to work (I think), but I'm not sure it's the correct way, or if there are any unforeseen drawbacks. Something just doesn't feel right about it.
这似乎有效(我认为),但我不确定这是正确的方法,或者是否有任何不可预见的缺点。只是感觉有些不对劲。
回答by Greg Hewgill
For string comparisons in Perl, use eq
or ne
:
对于 Perl 中的字符串比较,请使用eq
或ne
:
if ($str eq "")
{
// ...
}
The ==
and !=
operators are numericcomparison operators. They will attempt to convert both operands to integers before comparing them.
在==
与!=
运营商的数字比较操作符。在比较它们之前,它们将尝试将两个操作数转换为整数。
See the perlopman page for more information.
有关更多信息,请参阅perlop手册页。
回答by hobbs
Due to the way that strings are stored in Perl, getting the length of a string is optimized.
if (length $str)
is a good way of checking that a string is non-empty.If you're in a situation where you haven't already guarded against
undef
, then the catch-all for "non-empty" that won't warn isif (defined $str and length $str)
.
由于字符串在 Perl 中的存储方式,因此优化了获取字符串的长度。
if (length $str)
是检查字符串是否为非空的好方法。如果您处于尚未防范的情况下
undef
,那么不会警告的“非空”的全能是if (defined $str and length $str)
.
回答by DmitryK
You probably want to use "eq" instead of "==". If you worry about some edge cases you may also want to check for undefined:
您可能想使用“eq”而不是“==”。如果您担心某些边缘情况,您可能还想检查未定义:
if (not defined $str) {
# this variable is undefined
}
回答by Matthew Slattery
As already mentioned by several people, eq
is the right operator here.
正如几个人已经提到的,eq
这里是正确的运营商。
If you use warnings;
in your script, you'll get warnings about this (and many other useful things); I'd recommend use strict;
as well.
如果你use warnings;
在你的脚本中,你会得到关于这个(以及许多其他有用的东西)的警告;我也推荐use strict;
。
回答by whatsisname
The very concept of a "proper" way to do anything, apart from using CPAN, is non existent in Perl.
除了使用 CPAN 之外,做任何事情的“正确”方式的概念在 Perl 中都不存在。
Anyways those are numeric operators, you should use
无论如何,这些是数字运算符,您应该使用
if($foo eq "")
or
或者
if(length($foo) == 0)
回答by Roland Ayala
To check for an empty string you could also do something as follows
要检查空字符串,您还可以执行以下操作
if (!defined $val || $val eq '')
{
# empty
}