To check if a string starts with a specific prefix in Perl, you can use the index()
function or regular expressions.
In this example,
$str1
with a value of "Hello World"
.index()
function or regular expression to check if $str1
starts with the prefix "Hello"
.index()
function returns the starting position of the substring if found; otherwise, it returns -1
.$str1 = "Hello World";
$start_with_hello = index($str1, "Hello") == 0;
print "String starts with prefix 'Hello': $start_with_hello\n";
# or using regular expressions
$start_with_hello_regex = $str1 =~ /^Hello/;
print "String starts with prefix 'Hello' (using regex): $start_with_hello_regex\n";
String starts with prefix 'Hello': 1 String starts with prefix 'Hello' (using regex): 1
In this example,
$str2
with a value of "apple"
.index()
function or regular expression to check if $str2
starts with the prefix "banana"
.index()
function returns the starting position of the substring if found; otherwise, it returns -1
.$str2 = "apple";
$start_with_banana = index($str2, "banana") == 0;
print "String starts with prefix 'banana': $start_with_banana\n";
# or using regular expressions
$start_with_banana_regex = $str2 =~ /^banana/;
print "String starts with prefix 'banana' (using regex): $start_with_banana_regex\n";
String starts with prefix 'banana': String starts with prefix 'banana' (using regex):
In this tutorial, we learned How to Check if String starts with Specific Prefix in Perl language with well detailed examples.