在Perl中,可以使用defined
函數來判斷變量是否為空。defined
函數返回一個布爾值,如果變量已經被定義且不為空,則返回真,否則返回假。
以下是一個示例:
my $var1 = "";
my $var2;
my $var3 = "Hello";
if (defined $var1) {
print "var1 is defined\n";
} else {
print "var1 is not defined\n";
}
if (defined $var2) {
print "var2 is defined\n";
} else {
print "var2 is not defined\n";
}
if (defined $var3) {
print "var3 is defined\n";
} else {
print "var3 is not defined\n";
}
輸出結果為:
var1 is defined
var2 is not defined
var3 is defined
在這個示例中,$var1
被賦值為空字符串,$var2
未被賦值,$var3
被賦值為"Hello"。defined
函數分別判斷了這三個變量的狀態,并輸出相應的結果。