Monday, 27 January 2025

Perl Built-ins Quick Reference

1. String Functions

length

Returns the length of a string.

my $str = "Hello, World!";
my $len = length($str);
print "Length: $len\n";  # Output: Length: 13

substr

Extracts a substring from a string.

my $str = "Hello, World!";
my $sub = substr($str, 0, 5);
print "Substring: $sub\n";  # Output: Substring: Hello

index

Returns the position of a substring within a string.

my $str = "Hello, World!";
my $pos = index($str, "World");
print "Position: $pos\n";  # Output: Position: 7

rindex

Returns the last position of a substring within a string.

my $str = "Hello, World! World!";
my $pos = rindex($str, "World");
print "Last Position: $pos\n";  # Output: Last Position: 14

uc

Converts a string to uppercase.

my $str = "Hello, World!";
my $uc_str = uc($str);
print "Uppercase: $uc_str\n";  # Output: Uppercase: HELLO, WORLD!

lc

Converts a string to lowercase.

my $str = "Hello, World!";
my $lc_str = lc($str);
print "Lowercase: $lc_str\n";  # Output: Lowercase: hello, world!

ucfirst

Converts the first character of a string to uppercase.

my $str = "hello, world!";
my $ucfirst_str = ucfirst($str);
print "Ucfirst: $ucfirst_str\n";  # Output: Ucfirst: Hello, world!
Read more »

Labels: