How to Check String is empty or not in Perl with code example
This tutorial explains Multiple ways to check whether a given string is empty or not with Perl code examples.
- using string comparison operator,
eq
andne
,$str eq ""
or numeric comparison operator$str==""
- Another way using
length
function.length($str) == 0
Perl String Check Empty using string comparison operators
Perl provides the following String numeric operators.
eq
is an equal operator, Check given string is matched for another string. It returns true if matched, else return false.ne
is not an equal operator, the Reverse of theeq
operator.It returns false if matched, else return true.
String check empty using eq operator example
$str="";
if($str eq ""){
print "String is empty\n";
}
Output:
String is empty
``Similarly, another way to check String is empty or not using the`ne` operator.
```perl
$str="";
if($str ne ""){
print "String is not empty\n";
}else{
print "String is empty\n";
}
```
Output:
String is empty
``
## How to check String is blank or not using Numeric comparison operators
Perl provides the following numeric operators to check string contains an empty or not
- `==` is equal operator, Check given string is matched for another string
- `!=` is not equal operator, Reverse of `eq` operator.
String check blank using `==` operator example
```perl
$str="";
if($str == ""){
print "String is empty\n";
}
```
Output:
String is empty
``Similarly, another way to check String is empty or not using`!=` operator.
```perl
$str="";
if($str != ""){
print "String is not empty\n";
}else{
print "String is empty\n";
}
```
Output:
String is empty
``
## Check String is empty or not using the length function in Perl
Another way to check String is empty or not using the String length function.
`length` function returns the length of a String, the Number of characters in a String.
empty String contains no character, length returns zero.
use the `length` of a string code in a conditional if statement.
Here is an example
```perl
$str="";
if(length($str) == 0){
print "String is empty and length is zero"
}
```